How to unit test a class which calls service bus queue client SendAsync method

Sudama Tripathi picture Sudama Tripathi · Nov 10, 2016 · Viewed 11k times · Source

I have a interface which has a method to create instance of queue client and message factory. I have created a concrete implementation of the same and now i am trying to unit test the functionality which is used for send message to queue. I have written below code for the same:

private readonly Mock<IQueueClientProvider> queueClientProvider;

private readonly Mock<IJsonSerializer> jsonSerializer;

private readonly Mock<ILogger<QueueConnector>> logger;

private readonly ModelLogger<QueueConnector> modelLogger;

private readonly QueueConnector queueConnector;

private readonly Mock<QueueClient> queueClient;

public QueueConnectorTests() 

{

   queueClientProvider = new Mock< IQueueClientProvider >();

   queueClient = new Mock< QueueClient >();

   logger = new Mock< ILogger< QueueConnector >>();

   jsonSerializer = new Mock< IJsonSerializer >();

   modelLogger = new ModelLogger<QueueConnector>(logger.Object,     jsonSerializer.Object);

queueConnector = new QueueConnector(modelLogger, queueClientProvider.Object);

}

[Fact]
public async void ShouldBeAbleToSendMessage()

{

  BrokeredMessage brokeredMessage = new BrokeredMessage();

brokeredMessage.CorrelationId = "0HKVUFCD6Q5JL";

queueClientProvider.Setup(q =>q.CreateQueueClient()).Returns(queueClient.Object);

// Act

await queueConnector.SendMessage(brokeredMessage);

// Assert

 queueClient.Verify(q => q.SendAsync(brokeredMessage));


}

but getting exception

An exception of type 'System.NotSupportedException' occurred in mscorlib.dll but was not handled in user code

Additional information: Parent does not have a default constructor. The default constructor must be explicitly defined.

Can someone please help me with this not sure whats going wrong here?

Answer

Dibran picture Dibran · Nov 29, 2018

You should use the IQueueClient interface inside your code instead of the QueueClient implementation. The SendAsync method is part of the ISenderClient interface which IQueueClient inherits from.

Once you've used IQueueClient, you can do something like this:

var queueClientMock = new Mock<IQueueClient>();
queueClientMock.Setup(x => 
x.SendAsync(It.IsAny<Message>))).Returns(Task.CompletedTask).Verifiable();