有没有一种方法进行单元测试异步方法?方法、单元测试

2023-09-04 02:03:52 作者:一无所有就是打拼的理由i

我使用的xUnit和NMock在.NET平台。 我测试presentation模型,其中一个方法是异步的。 该方法创建一个异步任务,并执行它因此该方法立即返回,而我需要检查的状态都还没有准备好。

I am using Xunit and NMock on .NET platform. I am testing a presentation model where a method is asynchronous. The method creates an async task and executes it so the method returns immediately and the state I need to check aren't ready yet.

我可以设置完成后,一个标志,而无需修改SUT,但是这将意味着我将不得不继续检查的标志,例如一个while循环,有可能超时。

I can set a flag upon finish without modifying the SUT but that would mean I would have to keep checking the flag in a while loop for example, with perhaps timeout.

我有什么选择?

推荐答案

请问你的对象的功能,异步方法完成,如事件任何类型的信号?如果是这样的话,你可以用下面的办法:

Does your object feature any sort of signal that the asynchronous method is finished, such as an event? If that is the case, you can use the following approach:

[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);
}