x单元未等待异步测试
本文关键字:异步 测试 等待 单元 | 更新日期: 2023-09-27 17:57:21
在VS 2013上,我无法让这个异步测试失败。
我有xUnit 1.8.0.1539(从nuget安装),xUnit测试运行程序VS扩展名(0.99.5)。所有当前,AFAIK。
我碰巧在单元测试中也有Moq,AutoFixture和FluentAssertions引用,但我认为这并不重要(但我承认万一
)。我已经在解决方案的其他领域进行了异步单元测试,并且它们有效。
这个新创建的测试我错过了一些东西,我无法说出我错过了什么或做错了什么。
注意 SUT 代码并不意味着是完整的。我只是想先让红灯亮起,然后再编写代码以使测试变为绿色。
下面是测试代码:
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
namespace MobileApp.Proxy.Test
{
public class WhenRetrievingPriceDataFromClient
{
[Fact]
public async Task GroupReportIsReturnedWithSomeData()
{
// arrange
var sut = new Client();
// act
var actual = await sut.GetReportGroupAsync();
// assert
// Xunit test
Assert.Null(actual);
Assert.NotNull(actual);
// FluentAssertions
actual.Should().BeNull();
actual.Should().NotBeNull();
}
}
}
这是 SUT 代码:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MobileApp.Proxy.Properties;
namespace MobileApp.Proxy
{
public class Client
{
public async Task<ReportGroup> GetReportGroupAsync()
{
return await Task.FromResult(new ReportGroup());
}
}
}
显然,这个测试应该失败!Null 和 NotNull 的断言不能同时成功,所以我的结论是测试在完成从 SUT 获取响应之前退出。
我错过了什么?
或者,有没有更好的方法应该在编写 SUT 代码之前启动异步测试以确保它失败?
您需要 xUnit 1.9 才能async
单元测试正常工作。
xUnit v1.9 或更高版本支持异步测试。 如果您坚持使用早期版本,则需要执行以下操作:
[Fact]
public void GroupReportIsReturnedWithSomeData()
{
GroupReportIsReturnedWithSomeDataAsync().Wait();
}
private async Task GroupReportIsReturnedWithSomeDataAsync()
{
// arrange
var sut = new Client();
// act
var actual = await sut.GetReportGroupAsync();
// assert
// Xunit test
Assert.Null(actual);
Assert.NotNull(actual);
// FluentAssertions
actual.Should().BeNull();
actual.Should().NotBeNull();
}
基本上,测试方法会阻塞,直到异步测试方法完成,无论是由于成功完成还是错误(例如,断言失败)。 在发生故障的情况下,异常将通过Wait()
传播到主测试线程。
你可能希望将超时传递给Wait()
这样,如果测试在一段时间后仍未完成,测试将失败。 如前所述,如果异步方法从未完成,则测试可能会无限期阻塞。