2011-11-08 46 views
2

我有一个长时间运行的任务方法,使用睡眠异步CTP V3,MS测试和Thread.sleep代码

public Task LongRunning() { 
    return Task.Factory.StartNew(
     () => { 
      Trace.TraceInformation("Start Sleep"); 

      Thread.Sleep(10000); 

      Trace.TraceInformation("End Sleep"); 
     }); 
} 

这是我的测试调用,它工作正常

[TestMethod] 
public void SimpleContinueWith() { 
    Trace.TraceInformation("Start"); 

    LongRunning() 
     .ContinueWith(
      t => Trace.TraceInformation("End") 
     ).Wait(); 
} 

> QTAgent32.exe Information: 0 : Start 
> QTAgent32.exe Information: 0 : Start Sleep 
> QTAgent32.exe Information: 0 : End Sleep 
> QTAgent32.exe Information: 0 : End 

但使用异步/等待测试直接通过

[TestMethod] 
public async void SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 

> QTAgent32.exe Information: 0 : Start 
> QTAgent32.exe Information: 0 : Start Sleep 

为什么呢?

回答

4

MSTest不能(当前)处理异步测试。我不确定微软是否会在最终版本中添加这个功能。 更新:VS11测试版增加了对异步单元测试的支持;见下文。

您可以通过自己提供异步上下文来单元测试异步方法。有一些包含在Async CTP中(Microsoft Visual Studio异步CTP \ Samples \(C#测试)单元测试\ AsyncTestUtilities),或者您可以使用我编写的名为AsyncContext的一个。

使用AsyncContext,您的测试可以写为:

[TestMethod] 
public void SimpleAwait() { 
    AsyncContext.Run(async() => 
    { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
    }); 
} 

更新,2012-02-05:另一种选择是新AsyncUnitTests library。安装NuGet包,改变你的TestClassAsyncTestClass,你的异步单元测试可以更自然地写着:

[TestMethod] 
public async void SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 

更新,2012-06-06:如果更新到VS2012测试版,您可以定义异步单元测试;他们只需要返回Task

[TestMethod] 
public async Task SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 
+0

超,谢谢,安装NuGet包http://nuget.org/List/Packages/Nito.AsyncEx –

+0

顺便说一句,我在写测试的原因是因为我有一个调用Parallel.ForEach和递归的Async方法 - 它不能与async/await一起工作,就像上面的测试行为一样,即被调用并永不回来。 AsyncContext解决了这个问题 - 再次感谢 –