3

In my test constructor I set up my saga:

public When_Testing_My_Saga()
{
    _mySaga = new MySaga
    {
        Data = new MySaga.MySagaData()
    };
}

My test asserts that a failure is thrown on not receiving vital data:

[Fact]
public void Not_Providing_Data_Should_Cause_A_Failure()
{
    var context = new TestableMessageHandlerContext();

    Should.Throw<NoDataProvidedFailure>(() =>
    {
        _mySaga.Handle(new ImportDataReadMessage
        {
            ImportantData = null
        }, context).ConfigureAwait(false);
    });
}

The actual code in the SqlSaga:

public async Task Handle(ImportantDataReadMessage message, IMessageHandlerContext context)
{
    if (message.ImportantData == null)
    {
        throw new NoDataProvidedFailure("Important data was not provided.");
    }

    await context.Send(Endpoints.MyEndpoint, new DoStuffWhenImportantDataProvided
    {
        Reference = message.Reference
    });
}

Throws the expected failure but the test indicates the opposite:

Shouldly.ShouldAssertException _mySaga.Handle(new ImportantDataReadMessage { Reference = string.Empty, ImportantData = null }, context).ConfigureAwait(false); should throw Service.Failures.NoDataProvidedFailure but did not at Not_Providing_Data_Should_Cause_A_Failure () in mypath\When_Testing_My_Saga.cs:line 77

Which is really weird, because if I debug into the handler, the throw line IS hit.

Any clues to what may be going on?

PS: NoDataProvidedFailure inherits from Exception but is called a failure to indicate that it is unrecoverable (does not trigger retry).

Spikee
  • 3,967
  • 7
  • 35
  • 68

1 Answers1

6

Should be able to use Should.ThrowAsync with a Func<Task> to catch the exception on the correct thread to allow the test to be exercised as expected.

[Fact]
public async Task Not_Providing_Data_Should_Cause_A_Failure() {
    //Arrange
    var context = new TestableMessageHandlerContext();

    //Act
    Func<Task> act = () =>  _mySaga.Handle(new ImportDataReadMessage
                                {
                                    ImportantData = null
                                }, context);

    //Assert
    await Should.ThrowAsync<NoDataProvidedFailure>(act);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472