我正在尝试探索如何将 async 和 wait 关键字应用到我的 xUnit 测试中。我正在使用 xUnit 1.9 和 Async CTP 1.3。这是我的测试用例
我有一个接口,它指定一个异步方法调用
public interface IDoStuffAsync
{
Task AnAsyncMethod(string value);
}
我有一个类使用接口并调用异步方法
public class UseAnAsyncThing
{
private readonly IDoStuffAsync _doStuffAsync;
public UseAnAsyncThing(IDoStuffAsync doStuffAsync)
{
_doStuffAsync = doStuffAsync;
}
public async Task DoThatAsyncOperation(string theValue)
{
await _doStuffAsync.AnAsyncMethod(theValue);
}
}
在我的测试中我想检查该方法DoThatAsyncOperation
正在使用正确的值调用方法,因此我模拟接口并使用最小起订量来验证调用
[Fact]
public async void The_test_will_pass_even_though_it_should_fail()
{
var mock = new Mock<IDoStuffAsync>();
var sut = new UseAnAsyncThing(mock.Object);
mock.Setup(x => x.AnAsyncMethod(It.IsAny<string>()));
await sut.DoThatAsyncOperation("test");
// This won't throw a Moq.MockExcpetion so the test appears to pass
// However it does not run
mock.Verify(x => x.AnAsyncMethod("fail"));
}
本次测试使用的是async
and await
关键词。当它运行时,它会错误地通过,因为 Moq 应该断言验证失败。调用后的任何代码sut.DoThatAsyncOperation("test");
不运行
[Fact]
public void This_will_work_and_assert_the_reslt()
{
var mock = new Mock<IDoStuffAsync>();
var sut = new UseAnAsyncThing(mock.Object);
mock.Setup(x => x.AnAsyncMethod(It.IsAny<string>()));
sut.DoThatAsyncOperation("test").ContinueWith(y => { });
// This won't throw a Moq.MockExcpetion so the test appears to pass
// However it does not run
mock.Verify(x => x.AnAsyncMethod("fail"));
}
该测试的设置没有使用await 和async 关键字,并且顺利通过。
这是 xUnit 和 Moq 的预期行为吗?
Update
感谢斯蒂芬的评论,我设法通过进行两项更改来修复第一个测试。测试现在返回一个任务而不是 void,并且模拟也返回一个任务。
[Fact]
public async Task The_test_will_pass_even_though_it_should_fail()
{
var mock = new Mock<IDoStuffAsync>();
var sut = new UseAnAsyncThing(mock.Object);
mock.Setup(x => x.AnAsyncMethod(It.IsAny<string>())).ReturnAsync(true);
await sut.DoThatAsyncOperation("test");
// This now fails as it should
mock.Verify(x => x.AnAsyncMethod("fail"));
}