应该抛出单元测试失败但 saga 处理程序代码确实抛出不可恢复的异常

Should throw unit test fails but saga handler code does throw an unrecoverable exception

在我的测试构造函数中,我设置了我的传奇:

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

我的测试断言未收到重要数据会引发故障:

[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);
    });
}

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
    });
}

抛出预期的失败但测试表明相反:

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

这真的很奇怪,因为如果我调试处理程序,就会命中抛出线。

关于可能发生的事情的任何线索?

PS:NoDataProvidedFailure继承自Exception但称为失败表示不可恢复(不触发重试)

应该能够使用 Should.ThrowAsyncFunc<Task> 来捕获正确线程上的异常,以允许测试按预期进行。

[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);
}