对于异步代码的单元测试

问题描述 投票:9回答:4

我有一些代码,这是使用qazxsw POI类qazxsw POI方法,它是异步的。另外,我使用的测试应用微软的单元测试应用项目。

问题是,测试框架不会等待运行的异步代码的结束,所以我无法检查其结果。

我应该如何使用单元测试应用项目测试异步代码?我没有使用异步/等待变质剂。

c# unit-testing windows-phone-8
4个回答
5
投票

更新应答 原来答案是很旧的,HttpWebRequest.BeginGetResponse()是普遍。现在我建议你使用它们,写这样的:

async

有覆盖此深入await好文章

老回答

我会倾向于一些简单的像使用轮询循环和检查,将在异步代码进行设置,或者您可以使用重置事件的标志。使用线程一个简单的例子:

[TestMethod]
public async Task RunTest()
{
    var result = await doAsyncStuff();
    // Expectations
}

你需要考虑例外情况和使用try /终于和报告错误,正确地做到这一点,但你的想法。这个方法,如果你一遍又一遍地做大量的异步东西但是可能不适合,除非你看中推到一个可重用的方法这一点。


2
投票

你也可以使用异步/等待模式(使用来自Async Programming : Unit Testing Asynchronous Code[TestMethod] public void RunTest() { ManualResetEvent done = new ManualResetEvent(false); Thread thread = new Thread(delegate() { // Do some stuff done.Set(); }); thread.Start(); done.WaitOne(); } 包装)。这也将巧妙地处理发生在你的后台线程任何异常。

例如:

HttpWebRequest

0
投票

它的晚,但我想这将是更具可读性和正宗

Microsoft.Bcl.Async nuget package

-1
投票

检查接受[TestMethod] public void RunTest() { bool asyncDone = false; // this is a dummy async task - replace it with any awaitable Task<T> var task = Task.Factory.StartNew(() => { // throw here to simulate bad code // throw new Exception(); // Do some stuff asyncDone = true; }); // Use Task.Wait to pause the test thread while the background code runs. // Any exceptions in the task will be rethrown from here. task.Wait(); // check our result was as expected Assert.AreEqual(true, asyncDone); } ,使用Silverlight的单元测试框架进行单元测试异步代码。

© www.soinside.com 2019 - 2024. All rights reserved.