我想通过 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);
}
}
我的目标是将这两个测试合并为新的测试,但我想保留流畅的断言检查:result.Should().NotThrowAsync();
所以我的问题是在示例中如何检查返回值是17
的第一个测试?
答案 0 :(得分:2)
当前版本的Fluent断言(5.5.3)不能区分 Repetition
A regular expression may be followed by one of several repetition operators:
---------------------------------------------------------------
? The preceding item is optional and matched at most once.
---------------------------------------------------------------
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{,m} The preceding item is matched at most m times. This is a GNU extension.
{n,m} The preceding item is matched at least n times, but not more than m times.
和Func<Task>
。
两种类型都由Func<Task<T>>
处理,AsyncFunctionAssertions
将这两种类型分配给Func<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);
}
我已经在Fluent Assertion问题跟踪器上创建了issue。