有没有办法对异步方法进行单元测试?

Jih*_*Han 21 .net unit-testing xunit.net nmock

我在.NET平台上使用Xunit和NMock.我正在测试一个方法是异步的表示模型.该方法创建一个异步任务并执行它,以便该方法立即返回,我需要检查的状态尚未准备好.

我可以在完成时设置一个标志而不修改SUT但这意味着我必须继续检查while循环中的标志,例如,可能超时.

我有什么选择?

jus*_*ase 47

只是认为你可能想要对此进行更新,因为#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 ...
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,返回任务非常重要而不是无效:http://stackoverflow.com/questions/23824660/xunit-async-test-not-working-properly (2认同)

Fre*_*örk 20

您的对象是否具有异步方法完成的任何信号,例如事件?如果是这种情况,您可以使用以下方法:

[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);
}
Run Code Online (Sandbox Code Playgroud)