Search code examples
c#azureunit-testingazure-functionsazure-eventhub

Azure C# Cast Message object as EventData


I'm writing Unit Test for Azure Function. I'm trying to call AzureFunction Run method but she take EventData as parameter.

I'm working with Message such as:

var data = "fullJsonBody";
Newtonsoft.Json.Linq.JObject jsonBody = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(data);
Message messageToSend = new(Encoding.UTF8.GetBytes(jsonBody.ToString()));
messageToSend.Properties.Add("Prop1", "A");
messageToSend.Properties.Add("Prop2", "B");
messageToSend.Properties.Add("Prop3", "C");
messageToSend.Properties.Add("Prop4", "D");

_myModuleClient.SendEventAsync("Hub", messageToSend);

Now that i'm UnitTesting I want to directly call target Function such as:

public class MyAwesomeFunction
{
...

[FunctionName("MyMessages")]
    public async Task Run(
            [EventHubTrigger("HubTriggerExample", Connection = "HubConnectionStringExample", ConsumerGroup = "ConsumerGroupExample")]
            EventData[] events)
    {
        \\Work on Events
    }
    ...
}   

By calling function as any other function in C#.

MyAwesomeFunction.Run(????);

Unfortunatlly I don't know how to generate an EventData object from a Message object. Thanks for your help !


Solution

  • Ok I got it, I post what I have done for other.

    You can create an EventData with a Byte Array, so I just had to serialize my Car object as string, then encode it as Bytes[] and then create my EventData:

    var strCarObject = JsonConvert.SerializeObject(CarObject);
    byte[] carObjectByte = Encoding.UTF8.GetBytes(strCarObject);
    EventData dataCarObject = new EventData(carObjectByte);
    

    I don't need to use Message Properties in my case.