Having trouble triggering MassTransit consumer in xunit test

Viewed 183

I'm having 2 issues trying to unit test some code that uses MassTransit saga state machines and consumers. I'm using Autofac as a container and xUnit as a test framework.

I've got an example unit test here that illustrates both problems.

  1. When using just an Autofac container to set up my SagaStateMachine and Consumer, I can't assert that my state machine or consumer have consumed any messages - it seems as though they're not connected to the test bus.
    (test ExampleTest_AutofacOnly)

    I can get around this by introducing a ServiceCollection to the test and resolving the harnesses from the ServiceProvider instead of the IContainer but this feels like double handling.
    (test ExampleTest_AutofacAndServiceProvider)

  2. I cannot trigger my consumer using InMemoryTestHarness.Bus.Publish() (but I can trigger the state machine). What's really irritating is that I can trigger my state machine using InMemoryTestHarness.Bus.Publish(), and then the state machine can trigger the consumer when it handles the event.
    (tests ExampleTest2_AutofacOnly & ExampleTest2_AutofacAndServiceProvider)

EDIT

(2) doesn't seem to be a problem any more after I've commented out some lines. The equivalent lines in my example are:

// In my actual unit test the code below causes the test to fail
var state = sagaHarness.Sagas.Select(s => s.CorrelationId == correlationId).Single();
Assert.Equal("Progress state machine", state.Saga.Message);

// 4. Trigger the second consumer
await testHarness.Bus.Publish(new ExampleMessage2
{
    CorrelationId = correlationId,
    Message = "Trigger consumer",
});

// 5. Check that ExampleMessage has been published and received
Assert.True(await testHarness.Published.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));
Assert.True(await testHarness.Consumed.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));
Assert.True(await consumer2Harness.Consumed.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));

When I get the saga instance with sagaHarness.Sagas.Select() it prevents the message published below it from being consumed.

0 Answers
Related