Silverlight 异步单元测试 [英] Silverlight async unit testing

查看:48
本文介绍了Silverlight 异步单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Silverlight 单元测试框架时遇到了一个奇怪的问题.每次执行的第一个方法都会失败.我用完全相同的代码进行了第二次测试,它通过了.第一次调用它的奇怪之处在于它实际上等待超时然后执行存储库调用(如果您关心的话,它下面是一个 HTTP PUT).这是代码 - 第一个每次都失败,第二个每次都通过:

I'm having a weird issue with Silverlight Unit Test Framework. The very first method executed fails, every time. I have a second test with the exact same code, and it passes. The strange thing about the first time it's called is that it actually waits for the timeout and then executes the repository call (underneath it's an HTTP PUT if you care). Here's the code - the first one fails every time, second one passes every time:

    [TestMethod]
    public void AuthShouldSucceed()
    {
        var autoResetEvent = new AutoResetEvent(false);

        _authRepository.Authenticate(_username, _password, response =>
        {
            Assert.IsTrue(response);
            autoResetEvent.Set();
        });
        if (!autoResetEvent.WaitOne(Constants.Timeout))
        {
            Assert.Fail("Test timed out.");
        } 
    }

    [TestMethod]
    public void AuthShouldSucceed2()
    {
        var autoResetEvent = new AutoResetEvent(false);

        _authRepository.Authenticate(_username, _password, response =>
        {
            Assert.IsTrue(response);
            autoResetEvent.Set();
        });
        if (!autoResetEvent.WaitOne(Constants.Timeout))
        {
            Assert.Fail("Test timed out.");
        } 
    }

我的最终解决方案是对 Vladmir 解决方案的修改:

My final solution is a modification of Vladmir's solution:

    [TestMethod]
    [Asynchronous]
    public void AuthShouldSucceed()
    {
        var complete = false;
        var result = false;

        _authRepository.Authenticate(_username, _password, response =>
        {
            complete = true;
            result = response;
        });

        EnqueueConditional(() => complete);
        EnqueueCallback(() => Assert.IsTrue(result));
        EnqueueTestComplete();
    }

推荐答案

如果您正在使用 Silverlight 单元测试框架,请尝试以下面的方式重写您的测试:

If you're using Silverlight Unit Tests Framework try to rewrite your test next way:

    [TestMethod]
    [Asynchronous]
    public void AuthShouldSucceed()
    {
        var done = false;
        var authResult = false;
        _authRepository.Authenticate(_username, _password, response =>
        {
            var done = true;
            authResult = response;
        });

        EnqueueConditional(() => done);
        EnqueueCallback(() => Assert.IsTrue(authResult));
        EnqueueTestComplete();
    }

您的测试类应该从 SilverlightTest 类派生:

Your test class should be derived from SilverlightTest class:

[TestClass]
public class MyTests: SilverlightTest

这篇关于Silverlight 异步单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆