应该引发单元测试失败,但传奇处理程序代码的确引发不可恢复的异常

时间:2018-11-29 10:45:01

标签: c# nservicebus xunit shouldly

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

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);       应该抛出Service.Failures.NoDataProvidedFailure       但没有出现在mypath \ When_Testing_My_Saga.cs:line 77

中的Not_Providing_Data_Should_Cause_A_Failure()处

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

关于可能发生什么情况的任何线索?

PS:NoDataProvidedFailure从Exception继承,但是被称为失败,指示它是不可恢复的(不会触发重试)。

1 个答案:

答案 0 :(得分:6)

应该能够将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);
}