检查 FluentAssertion 异常语法中的返回值

rgb*_*rgb 0 c# nunit nsubstitute fluent-assertions

我想通过FluentAssertion语法检查方法的返回值。请考虑以下片段:

public interface IFoo
{
    Task<int> DoSomething();
}

public class Bar
{
    private readonly IFoo _foo;
    private static int _someMagicNumber = 17;

    public Bar(IFoo foo)
    {
        _foo = foo;
    }

    public async Task<int> DoSomethingSmart()
    {
        try
        {
            return await _foo.DoSomething();
        }
        catch
        {
            return _someMagicNumber;
        }
    }
}

[TestFixture]
public class BarTests
{
    [Test]
    public async Task ShouldCatchException()
    {
        // Arrange
        var foo = Substitute.For<IFoo>();
        foo.DoSomething().Throws(new Exception());
        var bar = new Bar(foo);
        Func<Task> result = () => bar.DoSomethingSmart();

        // Act-Assert
        await result.Should().NotThrowAsync();
    }

    [Test]
    public async Task ShouldReturnDefaultValueWhenExceptionWasThrown()
    {
        // Arrange
        var foo = Substitute.For<IFoo>();
        foo.DoSomething().Throws(new Exception());
        var bar = new Bar(foo);

        // Act
        var result = await bar.DoSomethingSmart();

        // Assert
        result.Should().Be(17);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是将这两个测试组合到新的测试中,但我想保留流畅的断言检查: result.Should().NotThrowAsync();

所以我的问题是如何检查返回值17在我的示例中的第一个测试?

Jon*_*rup 6

当前版本的 Fluent Assertions (5.5.3) 不区分Func<Task>Func<Task<T>>。这两种类型都由 处理AsyncFunctionAssertions,它将它分配给 aFunc<Task>并因此丢失 的返回值Task<T>

避免这种情况的一种方法是将返回值分配给局部变量。

[Test]
public async Task ShouldCatchException()
{
    // Arrange
    var foo = Substitute.For<IFoo>();
    foo.DoSomething().Throws(new Exception());
    var bar = new Bar(foo);

    // Act
    int? result = null;
    Func<Task> act = async () => result = await bar.DoSomethingSmart();

    // Act-Assert
    await act.Should().NotThrowAsync();
    result.Should().Be(17);
}
Run Code Online (Sandbox Code Playgroud)

我在 Fluent Assertion 问题跟踪器上创建了一个问题