Search code examples
unit-testingnservicebus

Better way to test nservicebus saga


I am trying to unit test the nservice saga and have written one test.

In that test there is one assert statement which is as below

Assert.IsType<MyCommand>(_messageContext.SentMessages[2].Message);

you can see that i have to use index 2 to get to that. In my saga i send many messages so its bit difficult to test by using Index. I tried to google but couldnt find any better solution.

Is there way like _messageContext.SentMessages("MyCommand").Message ?


Solution

  • If you don't care about the exact order that the messages are sent in, you could just use the Linq OfType method, as documented here, to find the ones of the relevant type:

    var myCommandMessage = _messageContext.SentMessages.OfType<MyCommand>().Single();
    

    This sounds more like a problem writing assertions elegantly than an NServiceBus specific issue. One way to write assertions more easily is to use a library such as FluentAssertions, which has very readable syntax for asserting e.g. that there is exactly one message in the collection of the specific type, and check that the message contents are correct.