Azure C# EventHubClient mock for unit test

时间:2017-07-12 08:16:54

标签: c# unit-testing azure-eventhub

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?

1 个答案:

答案 0 :(得分:0)

我只是在EventHubClient周围写了一个简单的包装,然后模拟了它。

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);
    }
}

然后测试很容易:var eventHubService = new Mock<IEventHubService>();