1

I need to write unit tests for the EventHubProducerClient class, which many instances of used in my repo. Modifying the original class is not an option. More specifically, I need to mock the CreateBatchAsync() method of the EventHubProducerClient class, as well as the SendAsync() method. Does anyone know how this can be accomplished? I am noob when it comes to mocking. Any help would be greatly appreciated, thanks

I tried creating a interface wrapper to implement the mock methods instead, but not only does this modify the original constructor, I also just couldn't get it to work. If you have any advice or solutions that would be very helpful (with code examples).

Jesse Squire
  • 6,107
  • 1
  • 27
  • 30

1 Answers1

1

To mock the CreateBatchAsync, you'll need to use the EventHubsModelFactory, which allows you to inject behavior to control what events the batch accepts and have access to the events that were added.

At a high level, this looks something like:

List<EventData> eventsInTheBatch = new();

EventDataBatch dataBatchMock = EventHubsModelFactory.EventDataBatch(
    batchSizeBytes : 500,
    batchEventStore : eventsInTheBatch,
    batchOptions : new CreateBatchOptions(),  
    eventData => eventsInTheBatch.Count < 5);

A full end-to-end example of mocking the EventHubProducerClient with batches can be found in the Mocking Client Types sample.

For more general information, the approach used to support unit testing in the Azure SDK libraries is described in the Azure SDK Design Guidelines and discussed further in Unit testing and mocking with Azure SDK .NET.

Jesse Squire
  • 6,107
  • 1
  • 27
  • 30