nunit: TestContext does not flow in async method
Example tests recreating issue:
[TestFixture]
public class TestContext_async_issue
{
[Test]
public async Task TestContext_Out_should_flow_with_async_execution()
{
var expected = TestContext.Out;
await Task.Yield();
Assert.AreSame(expected, TestContext.Out);
}
[Test]
public async Task TestContext_CurrentContext_should_flow_with_async_execution()
{
var expected = TestContext.CurrentContext;
await Task.Yield();
Assert.AreSame(expected, TestContext.CurrentContext);
}
}
The side effect of that behaviour is that it is not possible to use TestContext.WriteLine() after await as it causes NullReferenceException.
Tested with NUnit 3.5.0, net46 and netcoreapp1.0
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 1
- Comments: 28 (22 by maintainers)
The problem is that
TestExecutionContextis holding current context with[ThreadStatic]attribute (source code link).While it works fine in scenarios where multiple tests are executed in parallel (but each in given thread at a time), in async scenarios it will not work as each method continuation may execute in other thread. Replacement of
[ThreadStatic]with AsyncLocal<T> would be solution here, but unfortunately this class is available since .net 4.6 which is a pain for frameworks supporting older net versions 😦