简体   繁体   中英

How can I test for ConfigureAwait(false) in a unit test for async methods?

I have some async library methods where it is important the ConfigureAwait(false) be used "all the way down". I'd like to write an NUnit test that verifies that this is so. How can I do that? I imagine that I'd have to somehow hijack the synchronization context with a custom implementation?

I don't think this is possible. You could create a custom synchronization context (see striked answer below), but it would only check the first awaited call. If the first awaited call called uses ConfigureAwait(false) , the continuation will run on a different thread, which won't have a SynchronizationContext , so it won't be possible to check whether subsequent async calls use ConfigureAwait(false) or not.


Indeed, a custom synchronization context seems to be the only way. Here's a possible implementation:

 
 
 
  
  class TestSynchronizationContext : SynchronizationContext { public bool PostCalled { get; private set; } public override void Post(SendOrPostCallback d, object state) { PostCalled = true; base.Post(d, state); } public void Reset() { PostCalled = false; } }
 
  

You can then write your test like this:

 
 
 
  
  [Test] public void TestFoo() { var context = new TestSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(context); FooAsync().Wait(); Assert.IsFalse(context.PostCalled); }
 
  

if PostCalled is true, it means that the SynchronizationContext 's Post method was called, which shouldn't happen if ConfigureAwait(false) was used.

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