c# - Xamarin 中的 NUnit 异步测试不起作用

标签 c# mono nunit xamarin async-await

我是 C# 世界的新手,想给 Xamarin 一个评价。我一直在制作一个小型网络 api 库,到目前为止一切顺利,但现在我正在尝试测试网络组件,但遇到了一些麻烦。

OS:           OS X 10.9.1
Xamarin:      4.2.2 (build 2)
Library:      PCL targeting 4.0 (Profile158)
Nunit target: Mono / .NET 4.5

类/方法:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;

namespace LibTest
{
    public class AsyncTest
    {
        public async Task<string> DoTest()
        {
            return await new HttpClient().GetStringAsync( "http://www.reddit.com/.json?limit=1" );
        }
    }
}

NUnit 测试类/案例:

using System;
using NUnit.Framework;
using LibTest;

namespace LibTestTests
{
    [TestFixture]
    public class LibTestTest
    {
        [Test]
        public async void TempTest()
        {
            string data = await new AsyncTest().DoTest();

            Assert.IsNotNull( data );
            Assert.IsNull( data );
        }
    }
}

我的所有其他测试似乎都在工作(解析等),但这个测试只是通过了,就好像它通过了一样,但我不明白它是如何通过相互矛盾的断言的。

这是目前不支持的,还是我的实现不正确?

如果我让它与 ContinueWith()/Wait() 同步,它会按预期工作,但显然我不想在我的库中有重复的实现,只是为了通过测试。

最佳答案

NUnit 确实支持async Task 单元测试;不幸的是,Xamarin 使用的是旧版本的 NUnit,但它没有。但是,我不建议直接同步阻塞任务,因为这会使您的错误路径测试复杂化(异常包含在 AggregateException 中)。

我的 AsyncEx library 中有一个 AsyncContext 类型可以这样使用:

[Test]
public void TempTest()
{
    AsyncContext.Run(async () =>
    {
        string data = await new AsyncTest().DoTest();

        Assert.IsNotNull( data );
        Assert.IsNull( data );
    });
}

关于c# - Xamarin 中的 NUnit 异步测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20893238/

相关文章:

linux - 在 Linux (mono) 上运行的 TeamCity NUnitLauncher 出现 "Corlib not in sync with this runtime"错误

c# - nunit 如何成功等待 async void 方法完成?

c# - Enum.GetValues(typeof(....)) 没有返回正确的枚举值

c# - 如何在不属于任何选项卡内容(即登录部分或注册部分)的 JQuery 选项卡上延迟加载内容

c# - DJ 类效果算法的声音拉伸(stretch)

c# - 在列表上使用.Where()

c# - UDP通信快速填满内存

compilation - 在 Centos5 上为 Mono 编译 libgdiplus-2.10.9

jenkins - SonarQube 中未显示单元测试

c# - 通用抽象基类中的 NUnit 测试被忽略