Silverlight异步单元测试

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

[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,response =>
        {
            Assert.IsTrue(response);
            autoResetEvent.Set();
        });
        if (!autoResetEvent.WaitOne(Constants.Timeout))
        {
            Assert.Fail("Test timed out.");
        } 
    }

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

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

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

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

解决方法

如果您正在使用Silverlight Unit Tests Framework,请尝试下一步重写您的测试:

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

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

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

[TestClass]
public class MyTests: SilverlightTest

相关文章

如何在Silverlight4(XAML)中绑定IsEnabled属性?我试过简单的...
我正在编写我的第一个vb.net应用程序(但我也会在这里标记c#,...
ProcessFile()是在UIThread上运行还是在单独的线程上运行.如...
我从同行那里听说,对sharepoint的了解对职业生涯有益.我们不...
我正在尝试保存一个类我的类对象的集合.我收到一个错误说明:...
我需要根据Silverlight中的某些配置值设置给定控件的Style.我...