2012-10-25 27 views
0

我是使用VS2010的單元測試的新手。我試着做一個單元測試,調用WCF的託管。代碼如下所示:使用異步調用加載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

下面的代碼將考驗你異步方法,你必須在你等待主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); 
} 
+0

喜遺憾。這是我在編寫代碼時犯的一個錯誤。我已經調用client.GetDataAsync()。無論如何,測試仍然是0.我會再試一次。 – Bahamut