Search code examples
unit-testing.net-coremasstransitrouting-slip

How can I unit test a MassTransit consumer that builds and executes a routing slip?


In .NET Core 2.0 I have a fairly simple MassTransit routing slip that contains 2 activities. This is built and executed in a consumer and it all ties back to an automatonymous state machine. It all works great albeit with a few final clean tweaks needed.

However, I can't quite figure out the best way to write unit tests for my consumer as it builds a routing slip. I have the following code in my consumer:

public async Task Consumer(ConsumerContext<ProcessRequest> context)
{
   var builder = new RoutingSlipBuilder(NewId.NextGuid());

    SetupRoutingSlipActivities(builder, context);

    var routingSlip = builder.Build();

    await context.Execute(routingSlip).ConfigureAwait(false);
}

I created the SetupRoutingSlipActivities method as I thought it would help me write tests to make sure the right activities were being added and it simply looks like:

public void SetupRoutingSlipActivities(RoutingSlipBuilder builder, ConsumeContext<IProcessCreateLinkRequest> context)
{
        builder.AddActivity(
            nameof(ActivityOne),
            new Uri("execute_activity_one_example_address"),
            new ActivityOneArguments(
                context.Message.Id,
                context.Message.Name)
        );

        builder.AddActivity(
            nameof(ActivityTwo),
            new Uri("execute_activity_two_example_address"),
            new ActivityTwoArguments(
                context.Message.AnotherId,
                context.Message.FileName)
        );
}

I tried to just write tests for the SetupRoutingSlipActivities by using a Moq mock builder and a MassTransit InMemoryTestHarness but I found that the AddActivity method is not virtual so I can't verify it as such:

aRoutingSlipBuilder.Verify(x => x.AddActivity(
                nameof(ActivityOne),
                new Uri("execute_activity_one_example_address"),
                It.Is<ActivityOne>(y => y.Id == 1 && y.Name == "A test name")));

Please ignore some of the weird data in the code examples as I just put up a simplified version.

Does anyone have any recommendations on how to do this? I also wanted to test to make sure the RoutingSlipBuilder was created but as that instance is created in the Consume method I wasn't sure how to do it! I've searched a lot online and through the MassTransit repo but nothing stood out.


Solution

  • Look at how the Courier tests are written, there are a number of test fixtures available to test routing slip activities. While they aren't well documented, the unit tests are a working testament to how the testing is used.

    https://github.com/MassTransit/MassTransit/blob/develop/src/MassTransit.Tests/Courier/TwoActivityEvent_Specs.cs