帮助在Silverlight中编写异步单元测试

时间:2011-09-20 06:07:30

标签: c# silverlight unit-testing windows-phone-7

我正在尝试编写一个异步Silverlight单元测试,如http://developer.yahoo.com/dotnet/silverlight/2.0/unittest.html中所述。也许我正在努力使用lambda表达式,我不确定,但我不清楚如何编写我的命名回调,以便异步测试完成无例外。目前它在调用TestComplete()时抛出一个System.UnauthorizedAccessException(无效的跨线程访问),我猜这是因为它不知道它仍然在testNullInsert()测试中?

问题 - 如何正确编写测试,如果我需要lambda表达式,请解释一下该怎么做。

到目前为止,我的代码如下:

[TestClass]
public class IdentityEditDatabaseTest : WorkItemTest
{
  [TestMethod, Asynchronous] public void testNullInsert()
  {
    wipeTestData(testNullInsertContinue1);
  }
  private void testNullInsertContinue1(String errorString)
  {
    IdentityProperties properties = new IdentityProperties(getContext());
    properties.setUserName(DATABASE_TEST);
    postUserEdit(properties, testNullInsertContinue2);
  }
  private void testNullInsertContinue2(String errorString)
  {
    Assert.assertTrue(errorString == null);

    wipeTestData(testNullInsertContinue3);
  }
  private void testNullInsertContinue3(String errorString)
  {
    TestComplete();
  }
}

谢谢!

编辑:正确的代码在下面,感谢@ ajmccall的link

[TestClass]
public class IdentityEditDatabaseTest : DatabaseTestCase
{
  [TestMethod, Asynchronous] public void testNullInsert()// throws Throwable
  {
    EnqueueCallback(() => wipeTestData(errorString1 => {

    IdentityProperties properties = new IdentityProperties(getContext());
    properties.setUserName(DATABASE_TEST);
    EnqueueCallback(() => postUserEdit(properties, errorString2 => {

    Assert.assertTrue(errorString2 == null);

    EnqueueCallback(() => wipeTestData(errorString3 => {

    EnqueueTestComplete();
  }));
  }));
  }));
  }

2 个答案:

答案 0 :(得分:1)

TestComplete上会发生的一件事是UI将被更新。然而,显然TestComplete方法(或它最终与之交互的UI代码)不期望在非UI线程上调用。

因此,您可以确保在UI线程上执行对TestComplete的调用: -

  private void testNullInsertContinue3(String errorString)
  {
       Deployment.Current.Dispatcher.BeginInvoke(TestComplete); 
  }

答案 1 :(得分:1)

我认为@Anthony正确地建议TestComplete()调用UI线程,并且因为它是从后台线程调用的(因为它是一个回调),它会导致抛出此异常。 / p>

现在阅读文档时,它会显示[Asynchronous]标记

  

测试仅在调用TestComplete方法后完成,而不是在方法退出时完成。您的测试类必须从SilverlightTest继承以执行异步测试

您可以尝试将行TestComplete()放在testNullInsert方法的末尾。这可能不会抛出异常,但我认为它不会正确执行测试。你最终想要做的是有一个测试方法,它执行以下步骤,

  
      
  • 清除测试数据并等到它完成 - 这不是测试,所以不关心结果但我们仍然需要等待使用AutoResetEvent或继续回调
  •   
  • 定义您要测试的回调
  •   
  • 使用EnqueueCallback()
  • 将回调添加到单元测试队列   
  • 等待回调完成并存储结果 - 使用EnqueueConditional()
  •   
  • 通过调用EnqueueTestComplete()
  • 通知你已经完成的unti测试框架   

如果您可以将测试重写为类似this的内容,那么我认为您将开始为代码编写异步单元测试。

干杯, 人

相关问题