Michael Carter
Michael Carter

Reputation: 65

Unit Testing MassTransit Consumer With XUnit

My team is just getting started with using MassTransit and we are trying to figure out how unit testing IConsumer implementations work. The MassTransit documentation is incomplete and all of the examples I have found so far use NUnit. We are trying to use XUnit with Moq to do our unit testing.

I know that we need to set up one instance of the MassTransit test harness, which in NUnit is done with a OneTimeSetup and to replicate that we should use IClassFixture in XUnit. I'm struggling with getting that to work with the test harness, though.

I have seen Chris Patterson's ConsumerTest_Specs.cs example on the MassTransit GitHub, but I'm having a hard time translating it to work in XUnit and Moq. https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs

I'm trying to test a very simple consumer to start with. All it does is receive the message and then make a call to a repository. I want to write an XUnit test that mocks the repository and verifies that the repository method was called.

Does anyone have any examples of how to do something like this?

public class NewVMRequestRejectedConsumer : IConsumer<INewVMRequestRejected>
{
    private readonly INewVMRequestRepository _newVMRequestRepository;

    public NewVMRequestRejectedConsumer(INewVMRequestRepository newVMRequestRepository)
    {
        _newVMRequestRepository = newVMRequestRepository;
    }

    public Task Consume(ConsumeContext<INewVMRequestRejected> context)
    {
        _newVMRequestRepository.AddReasonForRejection(context.Message.RequestId, context.Message.Reason);
        return Task.CompletedTask;
    }
}

Upvotes: 3

Views: 2376

Answers (1)

Johnny
Johnny

Reputation: 9519

Since ConsumeContext<out T> and INewVMRequestRepository are interfaces there is no problem mocking them using moq, e.g.

//Arrange
var repository = new Mock<INewVMRequestRepository>();
var sut = new NewVMRequestRejectedConsumer(repository.Object);

//Act
sut.Consume(Mock.Of<ConsumeContext<INewVMRequestRejected>>(m =>
    m.Message.RequestId == "id" && m.Message.Reason == "reason"));

//Assert
repository.Verify(m => m.AddReasonForRejection("id", "reason"), Times.Once);

Upvotes: 2

Related Questions