简体   繁体   中英

How do I unit test Service Bus SendAsync method properly?

When running the unit test for Azure Service Bus method SendAsync I get the following exception on the line _queueClient.Verify() :

Expected invocation on the mock at least once, but was never performed: x => x.SendAsync({MessageId:})

This is my unit test:

public CustomerSendMsg(){ } //ctor

public async Task ShouldSendMessage()
{
    var _queueClient = new Mock<IQueueClient>();
    var _sut = new Publisher(_queueClient.Object);

    var customer = new Customer()
    {
        FirstName = "John",
        LastName = "Doe"
    };

    _queueClient.Setup(t => t.SendAsync(It.IsAny<Message>())).Returns(Task.CompletedTask).Verifiable();
    
    await _sut.SendMessageAsync(customer);
    
    var messageBody = JsonSerializer.Serialize(customer);
    var msg = new Message(Encoding.UTF8.GetBytes(messageBody));
    
    _queueClient.Verify(t = > t.SendAsync(msg));
}

This is SendMessageAsync method from the Publisher class:

public async Task SendMessageAsync<T>(T obj)
{
    var messageBody = JsonSerializer.Serialize(obj);
    var msg = new Message(Encoding.UTF8.GetBytes(messageBody));
    await _queueClient.SendAsync(msg);
}

Do you have any idea how can I make this unit test work?

Instead of creating a new message object which wouldn't work because the references are different - you could decode the body property from the Message class and verify the customer object's properties.

Instead of doing an object comparison (which is what Moq is doing), you can do the verification that the object being passed to the method has specific properties of the object using It.Is<T> .

_queueClient.Verify(t = > t.SendAsync(It.Is<byte[]>(x => x.Body == Encoding.UTF8.GetBytes(messageBody)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM