xUnit没有等待异步测试

Ala*_*SFT 17 c# tdd unit-testing asynchronous xunit.net

在VS 2013上,我无法让这个异步测试失败.

我有xUnit 1.8.0.1539(从nuget安装),xUnit Test Runner 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();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

这是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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,这个测试应该失败!Null和NotNull的断言不能同时成功,所以我的结论是测试在完成从SUT获得响应之前就退出了.

我错过了什么?

或者,有没有更好的方法我应该在编写SUT代码之前启动异步测试以确保它失败?

Ste*_*ary 25

您需要xUnit 1.9才能使async单元测试正常工作.


Mik*_*bel 5

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();
}
Run Code Online (Sandbox Code Playgroud)

基本上,测试方法会阻塞,直到异步测试方法完成,无论是由于成功完成还是故障(例如,断言失败).在出现故障的情况下,异常将传播到主测试线程Wait().

您可能希望传递超时,Wait()以便在一定时间后未完成测试将失败.如上所述,如果异步方法永远不会完成,则测试可能会无限期地阻塞.