Home > Software design >  Azure.Messaging.EventGrid vs Azure.EventGrid IotHubDeviceTelemetryEventData missing Constructor?
Azure.Messaging.EventGrid vs Azure.EventGrid IotHubDeviceTelemetryEventData missing Constructor?

Time:10-14

I am attempting to use the newer Azure.Messaging.EventGrid over the traditional Azure.EventGrid. I am getting hung up on my unit tests attempting to create object of type IotHubDeviceTelemetryEventData(). In the older library, I was able to create this no problem using the following convention.

  return new object[]
            {
                new
                {
                    id = "73813f6e-4d43-eb85-d6f1-f2b6a0657731",
                    topic = "testTopic",
                    data = new IotHubDeviceTelemetryEventData <-- New Up the object (no problem!) 
                    {
                        Body = body} <-- Body has a setter. Great!
                    ,
                    eventType = "Microsoft.Devices.DeviceTelemetry",
                    subject = "devices/b82bfa90fb/gw-uplink",
                    dataVersion = "1.0"
                }

With the latest offering however, all of this is removed for some reason.

Old documentation with constructor etc (https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventgrid.models.iothubdevicetelemetryeventdata.-ctor?view=azure-dotnet

New documentation with no constructor, no setter on the body (DeviceTelemetry is sealed) etc: https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventgrid.systemevents.iothubdevicetelemetryeventdata?view=azure-dotnet

Anyone run into this? I would like to get off the old but I have existing unit tests that logically create TelemetryEventData and send to the function. I see no way of unit testing this ? I have tried mocking IotHubDeviceTelemetryEventData with _mockHubTelemEventData.setup(c => c.Body).Returns(foo) but this as well throws me an error of no setter on Body.

Super frustrating. Other attempts have included creating EventGridEvent() but this as well is missing core functionality as the EventGridEvent.parse won't find any object of type Body. EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(req.Body));

CodePudding user response:

Mocking code you don't own comes with downsides, and you just one of them. But that's not why you're here. If you want to create instances of IotHubDeviceTelemetryEventData, you can try creating them as JSON and deserialize them. Give this a shot:

using System.Text.Json;
using Azure.Messaging.EventGrid.SystemEvents;

var json = @"
{
    ""body"": 
        { 
            ""property"": { ""foo"": ""bar"" }
        }
}
";

var eventData = JsonSerializer.Deserialize<IotHubDeviceTelemetryEventData>(json);
  • Related