我使用 xUnit 和 FluentAssertions 编写单元测试,但遇到以下问题。由于我还没有实现catch
(in GetCountriesAsync
) 的,我在这个地方WebException
扔了一个新的。NotImplementedException
这段代码是我使测试真正按预期工作的唯一方法。我也添加了本机 xUnit 实现,因为 FluentAssertions 只是语法糖。
[Fact]
public async Task GetCountriesAsyncThrowsExceptionWithoutInternetConnection()
{
// Arrange
Helpers.Disconnect(); // simulates network disconnect
var provider = new CountryProvider();
try
{
// Act
var countries = await provider.GetCountriesAsync();
}
catch (Exception e)
{
// Assert FluentAssertions
e.Should().BeOfType<NotImplementedException>();
// Assert XUnit
Assert.IsType<NotImplementedException>(e);
}
}
虽然我发现这个实现要好得多,但它就是行不通。
[Fact]
public async Task GetCountriesAsyncThrowsExceptionWithoutInternetConnection3()
{
// Arrange
Helpers.Disconnect(); // simulates network disconnect
var provider = new CountryProvider();
// Act / Assert FluentAssertions
provider.Invoking(async p => await p.GetCountriesAsync())
.ShouldThrow<NotImplementedException>();
// Act / Assert XUnit
Assert.Throws<NotImplementedException>(async () => await provider.GetCountriesAsync());
}
由于 VS2012/ReSharper 已经建议删除async
测试方法的冗余关键字,我替换async Task
为void
并且测试仍然表现相同,所以我怀疑 asyncAction
不能等待,它们相当被解雇和遗忘。
有没有办法用 xUnit/FluentAssertions 正确实现这一点?我想我必须使用我的第一个实现,因为我看不到任何类似InvokingAsync()
.