.NET: Unit Testing Azure Service Bus

Unit testing an Azure Service Bus consumer is fairly easy. In this tutorial, I will use .NET6, Moq (v4), and Fluent Assertions. The difficult part is constructing the ServiceBusMessageReceived because it has only internal constructors and no interface. However, there is a factory service that can create these objects.


I’ve included unit testing in this project.



What should be unit tested?

There are two areas that I focus on when testing consumer service. That is message processing and error handling.

Message Handler

This is the main method for processing incoming data from Azure Service Bus. This can be tested to make sure data is properly deserialized, and distributed to the correct services appropriately.

Error Handler

The Error Handler method can handle specific cases where the service bus client fails. It may be useful to unit test this code if there are certain actions that need to happen during a failure.

ConsumerAzureServiceBus Service Class

This is the code that we will be testing to put things in context.

Mocking the Service Bus Client

I’ve tried these several ways and I think this is the simplest. Moq can only mock public and virtual methods. An easy and effective way to implement a mocked Service Bus Client is to create a public virtual method that returns the service bus client. I’m also excluding this from code coverage since this is specifically here for unit testing.

In the StartReceivingMessageAsync() method I can get the client doing this.

Why injecting the ServiceBusClient didn’t work out.

Someone recommended injecting the ServiceBusClient and I thought that was worth trying. That doesn’t work in the end for several reasons. There isn’t a method to connect or reconnect that I know of and the only way a connection is created is through instantiating the ServiceBusClient service. When the subobject object processor is disposed it causes the service bus client to close which will no longer maintain a connection and will cause the service to fail.

ServiceBusModelFactory Factory Class

The Service Bus Model Factory can be used to mock the ServiceBusReceivedMessage class.

Message Handler Tests

The general idea here is that we want to test the flow of the message handler to make sure it’s passing and accepting the correct arguments. Typically after consumption either a message is saved in a database or passed to another service for further processing. We want to make sure that everything happens here as expected.

Error Handler Tests

This is just a sample of what could be tested.

Full Unit Tests

Again all of this is on my GitHub under the Microservice: Application Insights repository.