我在Silverlight单元测试框架中遇到了一个奇怪的问题。每次执行的第一个方法都会失败。我有第二个测试完全相同的代码,并通过。第一次被调用的奇怪之处在于它实际上等待了超时,然后执行了存储库调用(如果你在意的话,它下面是一个HTTP PUT)。下面的代码 - 第一个失败每一次,第二个通过每次:Silverlight异步单元测试
[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.");
}
}
编辑: 我的最终解决方案是弗拉基米尔·解决方案的修改:
[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();
}
这真棒,我会改变一件事。这是有效的,因为'Authenticate'巧合地返回'true'。如果我正在测试'false'或者返回了一些其他对象,它将无法工作。基本上我修改了这个答案,无论返回类型如何 - 我使用了一个像上面提到的一样的'done'变量(以及结果变量)。 – user140550 2012-07-19 20:46:36
当然,你是对的,适当地更新答案 – 2012-07-19 20:53:02