2

我有一个在不同线程中执行某些功能的类。我想在我的 MonoTouch 应用程序中测试这个类。所以我在测试项目中添加了一个测试夹具。我发现 MonoTouch 不会等待测试完成,它只是在测试用例仍在运行时说它“成功”。案例示例如下:

[Test]
public void ThreadTest()
{
    Timer ApplicationTimer = new Timer {Enabled = true, Interval = 2500};
    ApplicationTimer.Elapsed += ApplicationTimer_Tick;
}

private void ApplicationTimer_Tick (object sender, ElapsedEventArgs e)
{
   Assert.Fail("failing"); // by the time the debugger hits this point, the UI already says that all tests passed. which is totally wrong. 
}

任何帮助,将不胜感激。

4

1 回答 1

3

这不是 MonoTouch 特定的问题 - 该测试在所有测试运行程序中都会失败。

等待此异步事件的测试可能如下所示:

        private ManualResetEvent _mre = new ManualResetEvent(false);

        [Test]
        public void ThreadTest()
        {
            Timer ApplicationTimer = new Timer {Enabled = true, Interval = 2500};
            ApplicationTimer.Elapsed += ApplicationTimer_Tick;
            if (!_mre.WaitOne(3000))
            {
                Assert.Fail("Timer was not signalled");
            }
        }

        private void ApplicationTimer_Tick (object sender, ElapsedEventArgs e)
        {
            _mre.Set();             
        }

但是你在编写这种测试时必须非常小心,以确保你没有锁定线程、跨测试重用对象等。

于 2013-05-15T10:23:18.893 回答