简体   繁体   English

正常运行时阻塞,但在单元测试期间不阻塞(StoreAsync)

[英]blocking when run normally, but not during unit tests (StoreAsync)

I have an issue here where during unit tests, the StoreAsync() method returns. 我这里有一个问题,在单元测试期间,StoreAsync()方法返回。 When run without debugging, it seems to never return even though it is an async method. 如果在没有调试的情况下运行,即使它是异步方法,它似乎也永远不会返回。

What gives? 是什么赋予了?

   DataWriter writer = new DataWriter(_client.OutputStream);
   writer.WriteBytes(payload);
   await writer.StoreAsync(); // <--- returns only during unit test
   writer.DetachStream();

If you're using VS 11 Beta, then make sure your unit test is declared as async Task . 如果您使用的是VS 11 Beta,请确保将单元测试声明为async Task

If you're using VS 11 Dev Preview, then use the Async Unit Tests project from CodePlex. 如果您使用的是VS 11 Dev Preview,请使用CodePlex的“ 异步单元测试”项目

I have more information on async unit tests on my blog ( part 1 , part 2 ). 我在我的博客上有关于异步单元测试的更多信息( 第1 部分第2部分 )。 In summary: 综上所述:

  1. When await needs to (asynchronously) wait, it schedules a continuation and returns to its caller. await需要(异步)等待时,它将安排继续操作并返回其调用方。
  2. MSTest sees the test method return, does not see any exceptions, and marks it as "passed". MSTest看到测试方法返回,没有看到任何异常,并将其标记为“通过”。
  3. Later on, the StoreAsync will complete and the rest of the method will run (on a thread pool thread, not within the context of that unit test). 稍后, StoreAsync将完成,其余方法将运行(在线程池线程上,而不是在该单元测试的上下文中)。

VS 11 Beta adds first-class support for async Task unit test methods. VS 11 Beta添加了对async Task单元测试方法的一流支持。 So the second step above is different: MSTest sees the test method return but knows not to consider it complete until the Task completes. 因此,上面的第二步是不同的:MSTest看到测试方法返回,但是知道在Task完成之前不认为它已完成。

The Async Unit Tests project takes a different approach: it applies an async context for every unit test method in an [AsyncTestClass] . 异步单元测试项目采用了不同的方法:它为[AsyncTestClass]中的每个单元测试方法应用了一个异步上下文。 This async context waits for all asynchronous operations to complete (including async void methods) before completing the unit test. 此异步上下文在完成单元测试之前等待所有异步操作(包括async void方法)完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM