使用对WCF的异步调用进行负载测试

时间:2012-10-25 08:52:00

标签: c# visual-studio-2010 wcf unit-testing

在使用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

1 个答案:

答案 0 :(得分:1)

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

[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);
}
相关问题