Search code examples
c#.netnservicebusxunitacceptance-testing

How to get feedback from saga handler using NServiceBus Acceptance Testing


Background

I have written a test that makes sure that the command that should start my saga effectively creates the saga and that it's handler code can be executed:

[Fact]
public async Task Can_Start_Saga_And_Execute_Handler()
{
    var result = await Scenario
        .Define<Context>()
        .WithEndpoint<Endpoint>(b => b.When(session =>
            {
                return session.SendLocal(new SagaStarter());
            })
        )
        .Done(context => context.IsRequested)
        .Run(Testing.MaxRunTime);

    result.IsRequested.ShouldBeTrue();
}

Where Context is:

class Context : ScenarioContext
{
    public bool IsRequested { get; set; }
}

So

If I have a handler in my saga definition like so:

public async Task Handle(SagaStarter message, IMessageHandlerContext context)
{
    await StuffToDo();
}

How can I ensure that the IsRequested property, defined in Context, is set to true from within the saga?


Solution

  • I've found a solution, adding an extra message handler in the test like so:

    public class TestHandler : IHandleMessages<SagaStarter>
    {
        private Context _testContext;
    
        public TestHandler(Context testContext)
        {
            _testContext = testContext;
        }
    
        public Task Handle(SagaStarter message, IMessageHandlerContext context)
        {
            _testContext.IsRequested= true;
            return Task.CompletedTask;
        }
    }
    

    The Context parameter is inserted through Dependency Injection.