本文介绍了如何使用Xamarin iOS TouchRunner对UI线程上的异步方法进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have successfully been able to get the following nested async unit test working using TouchRunner (NUnitLite) in Xamarin:

[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更改,从而在主线程上执行该怎么办?以下是我尝试执行此操作的尝试,但是仍然存在一些问题...

However, what if I want to test an async method that needs to perform some logic but also make some UI changes and thus, be executed on the main thread? Below is my attempt at doing this however, there are some issues...

[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);
}

使用超时"属性,TouchRunner可能由于线程锁定而冻结.如果没有Timeout属性,则断言将返回false-我相信这是由于async方法未正确等待吗?

With the Timeout attribute the TouchRunner freezes probably due to some thread locking. Without the Timeout attribute, the assertion returns false - I believe this is due to the async method not awaiting properly?

谁能告诉我我要去哪里错了,和/或如何做到这一点?

Can anyone advise where I'm going wrong and/or how this can be accomplished?

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

My use of the Timeout attribute in the first test is explained here:https://bugzilla.xamarin.com/show_bug.cgi?id=15104

推荐答案

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

I've used an AutoResetEvent in situations like these to test our asynchronous startup routines:

[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流程.

If you're testing UI functionality, you may be better using Calabash or a related framework that is dedicated to testing UI flow.

这篇关于如何使用Xamarin iOS TouchRunner对UI线程上的异步方法进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 09:10