Search code examples
unit-testingnservicebussaga

How to create unit tests for NServiceBus Saga when Saga has more than one handler


I used to have this test, which passes just fine (The saga is complete once all three messages have been handled.

        Test.Saga<TestSagaHandler>(sagaId)
            .When(x =>
            {
                x.Handle(new TestSagaStartMessageOne
                {
                    Id = sagaId
                });
                x.Handle(new TestSagaStartMessageTwo
                {
                    Id = sagaId
                });
                x.Handle(new TestSagaNonStartingMessage
                {
                    Id = sagaId
                });
            });
            .AssertSagaCompletionIs(true);

I now want to break out the TestSagaNonStartingMessage into its own handler, and did the following:

        Test.Saga<TestSagaHandler>(sagaId)
            .When(x =>
            {
                x.Handle(new TestSagaStartMessageOne
                {
                    Id = sagaId
                });
                x.Handle(new TestSagaStartMessageTwo
                {
                    Id = sagaId
                });
            });

        Test.Saga<TestSagaHandlerSingleMessage>(sagaId)
            .When(x =>
                x.Handle(new TestSagaNonStartingMessage
                {
                    Id = sagaId
                })
            )
        .AssertSagaCompletionIs(true);

However, when handling the TestSagaNonStartingMessage - the saga data is not persisted from the previous handlers.

Am I having persistence problems, or is the test constructed badly?


Solution

  • For other readers reference, the proper test structure should be similar to:

        Test.Saga<TestSagaHandler>(sagaId)
            .When(x =>
            {
                x.Handle(new TestSagaStartMessageOne { Id = sagaId });
                x.Handle(new TestSagaStartMessageTwo { Id = sagaId });
            })
            .When(x =>
                x.Handle(new TestSagaNonStartingMessage { Id = sagaId })
            )
            .AssertSagaCompletionIs(true);
    

    As Udi indicated, chain the "When" clauses together.

    Also, in order to derive further value from the test, consider introducing exceptions, such as ExpectSend<>, ExpectPublish, etc.

    Reference: http://docs.particular.net/nservicebus/testing/