ios - 如何使用 Xamarin iOS TouchRunner 在 UI 线程上对异步方法进行单元测试

标签 ios iphone unit-testing asynchronous xamarin

我已经能够在 Xamarin 中使用 TouchRunner (NUnitLite) 成功获得以下嵌套异步单元测试:

[Test]
[Timeout (Int32.MaxValue)]
public async void NestedAsyncFail()
{
    await Task.Run(async() =>
    {
        await Task.Delay(1000);
    });

    Assert.AreEqual(1, 0);
}

[Test]
[Timeout (Int32.MaxValue)]
public async void NestedAsyncSuccess()
{
    await Task.Run(async() =>
    {
        await Task.Delay(1000);
    });

    Assert.AreEqual(1, 1);
}

结果:http://i.stack.imgur.com/5oC11.png

但是,如果我想测试一个异步方法,它需要执行一些逻辑,但也需要做一些 UI 更改,因此在主线程上执行怎么办?以下是我尝试这样做的尝试,但是存在一些问题......

[Test]
[Timeout (Int32.MaxValue)]
public void TestWithUIOperations()
{
    bool result = false;

    NSObject invoker = new NSObject ();
    invoker.InvokeOnMainThread (async () => {
        await SomeController.PerformUIOperationsAsync ();
        result = true;
    });

    Assert.True (result);
}

使用 Timeout 属性时,TouchRunner 可能由于某些线程锁定而卡住。如果没有 Timeout 属性,断言将返回 false - 我认为这是由于异步方法未正确等待造成的?

谁能告诉我哪里出错了和/或如何实现?

我在第一个测试中对 Timeout 属性的使用说明如下: https://bugzilla.xamarin.com/show_bug.cgi?id=15104

最佳答案

我在这些情况下使用了 AutoResetEvent 来测试我们的异步启动例程:

[Test]
public void CanExecuteAsyncTest()
{
    AutoResetEvent resetEvent = new AutoResetEvent(false);
    WaitHandle[] handles  = new WaitHandle[] { resetEvent};

    bool success = false;

    Thread t = new Thread(() => {
        Thread.Sleep(1000);
        success = true;
        resetEvent.Set();
    });

    t.Start ();

    WaitHandle.WaitAll(handles);

    Assert.Equal(true, success);
}

如果您正在测试 UI 功能,您最好使用 Calabash或专用于测试 UI 流程的相关框架。

关于ios - 如何使用 Xamarin iOS TouchRunner 在 UI 线程上对异步方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676672/

相关文章:

iphone - iOS 本地化 : Create strings-file for native language?

iphone - 我们如何在 UIButton 上添加 UIPopOverController?

iphone - 如果标签相等,则更改 View

ios - 为 iOS 增强现实应用程序开发自定义过滤器

c# - 如何使用 FluentAssertion 测试一个对象是否与已设置了 Solidcolorbrush 属性的另一个对象等效

unit-testing - 使用 Moq 模拟返回值的存储库

java - 如何开始测试(jMock)

ios - Facebook App 中的 Graph API 与 iOS SDK

ios - 为什么我的 Xcode 没有 'using local signing assets' 选项

IOS: ScrollView 中的声音