0

在使用 VS2010 的单元测试时,我是新手。我尝试进行单元测试以调用托管的 WCF。代码如下所示:

...
[TestMethod]
public void TestMethod1()
{
   WcfClient client = new WcfClient("BasicHttpBinding_IWcf");
   client.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(OnGetDataCompleted);
   client.GetDataAsync(arg1, arg2);
}

void OnGetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
   Assert.IfNull(e.Error);
}

...

当我运行它时,它似乎从未启动或完成。我正在考虑将其添加到负载测试中。我是否遗漏了什么来测试对 WCF 的异步调用?我听说过 codeplex 中的 WCF 负载测试,但我会再讲一遍。

同行答案的变体:http: //justgeeks.blogspot.com/2010/05/unit-testing-asynchronous-calls-in.html

4

1 回答 1

1

以下代码将测试您的异步方法,您必须在主线程中等待并在那里执行断言:

[TestMethod]
public void TestMethod1()
{
  WcfClient client = new WcfClient("BasicHttpBinding_IWcf");

  AutoResetEvent waitHandle = new AutoResetEvent(false); 

  GetDataCompletedEventArgs args = null;
  client.GetDataCompleted = (s, e) => {
    args = e.Error;
    waitHandle.Set(); 
  };

  // call the async method
  client.GetDataAsync(arg1, arg2);

  // Wait until the event handler is invoked
  if (!waitHandle.WaitOne(5000, false))  
  {  
    Assert.Fail("Test timed out.");  
  }  

  Assert.IfNull(args.Error);
}
于 2012-10-25T08:55:22.710 回答