6

I am writing an event publisher for our application which internally uses Azure C# EventHubClient.

I want to unit test that my event gets translated correctly into EventData object (Properties + Body) as well as some other features. Long story short, I need some way to create a mock for EventHubClient. Unfortunately, there does not seem to be a simple way of doing that:

  • EventHubClient does not implement any relevant interface so using something like Moq or NSubstitute to create a mock will not work.
  • EventHubClient is an abstract class with internal constructor so I cannot extend it and create a custom mock.

In theory, I could create a wrapper interface and class around the methods I want to use, but it means having more code to maintain. Does anybody know about a better way of unit testing with EventHubClient?

Richard Sirny
  • 61
  • 1
  • 4
  • Take a look at how they test it and see if it sheds some light on the subject https://github.com/Azure/azure-event-hubs-dotnet/tree/dev/test/Microsoft.Azure.EventHubs.Tests – Nkosi Jul 12 '17 at 09:59
  • @Nkosi thanks for the tip. They are loading connection string for real Event Hub from environment variables so it's more like integration test... I guess it makes sense for their use case. – Richard Sirny Jul 12 '17 at 15:59
  • @Nkosi In the end, I found the answer [in the repo](https://github.com/Azure/azure-event-hubs-dotnet/issues/24): the unit test friendliness should be coming soon. – Richard Sirny Jul 12 '17 at 16:06
  • 2
    I don't think Microsoft is big into "soon" - they've only been rejecting PR's thus far. – kdazzle Jan 11 '19 at 20:31

1 Answers1

3

I just wrote a simple wrapper around the EventHubClient and mocked that up instead.

public class EventHubService : IEventHubService
{
    private EventHubClient Client { get; set; }

    public void Connect(string connectionString, string entityPath)
    {
        var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = entityPath
            };

        Client =  EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
    }

    public async void Disconnect()
    {
        await Client.CloseAsync();
    }

    public Task SendAsync(EventData eventData)
    {
        return Client.SendAsync(eventData);
    }
}

And then testing is easy: var eventHubService = new Mock<IEventHubService>();

kdazzle
  • 4,190
  • 3
  • 24
  • 27