简体   繁体   中英

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

I have an issue here where during unit tests, the StoreAsync() method returns. 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 .

If you're using VS 11 Dev Preview, then use the Async Unit Tests project from CodePlex.

I have more information on async unit tests on my blog ( part 1 , part 2 ). In summary:

  1. When await needs to (asynchronously) wait, it schedules a continuation and returns to its caller.
  2. MSTest sees the test method return, does not see any exceptions, and marks it as "passed".
  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).

VS 11 Beta adds first-class support for async Task unit test methods. So the second step above is different: MSTest sees the test method return but knows not to consider it complete until the Task completes.

The Async Unit Tests project takes a different approach: it applies an async context for every unit test method in an [AsyncTestClass] . This async context waits for all asynchronous operations to complete (including async void methods) before completing the unit test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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