Dot-Net
有沒有辦法對非同步方法進行單元測試?
我在 .NET 平台上使用 Xunit 和 NMock。我正在測試一個方法是非同步的表示模型。該方法創建一個非同步任務並執行它,因此該方法立即返回並且我需要檢查的狀態還沒有準備好。
我可以在不修改 SUT 的情況下在完成時設置一個標誌,但這意味著我將不得不在一個 while 循環中繼續檢查標誌,例如,可能會超時。
我有哪些選擇?
您的對像是否具有非同步方法完成的任何類型的信號,例如事件?如果是這種情況,您可以使用以下方法:
[Test] public void CanTestAsync() { MyObject instance = new MyObject() AutoResetEvent waitHandle = new AutoResetEvent(false); // create and attach event handler for the "Finished" event EventHandler eventHandler = delegate(object sender, EventArgs e) { waitHandle.Set(); // signal that the finished event was raised } instance.AsyncMethodFinished += eventHandler; // call the async method instance.CallAsyncMethod(); // Wait until the event handler is invoked if (!waitHandle.WaitOne(5000, false)) { Assert.Fail("Test timed out."); } instance.AsyncMethodFinished -= eventHandler; Assert.AreEqual("expected", instance.ValueToCheck); }
只是認為您可能需要對此進行更新,因為#1 答案實際上是推荐一種較舊的模式來解決此問題。
在 .net 4.5 + xUnit 1.9 或更高版本中,您可以簡單地返回一個 Task 並可選擇使用測試中的 async 關鍵字讓 xunit 等待測試非同步完成。
請參閱xUnit.net 1.9上的這篇文章
[Fact] public async Task MyAsyncUnitTest() { // ... setup code here ... var result = await CallMyAsyncApi(...); // ... assertions here ... }