Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NUnit TestContext.CurrentContext safe to use in parallel tests?

Background

An NUnit framework extension that I'm working on needs to know the outcome/result of each test from within an ITestAction attribute, like so:

public class MyFrameworkExtensionAttribute : Attribute, ITestAction
{
  public void BeforeTest(ITest test)
  { /* Omitted, not relevant to this question */ }

  public void AfterTest(ITest test)
  {
    var result = TestContext.CurrentContext.Result;
    var resultIsSuccess = result.Outcome.Status == TestStatus.Passed;
    // Then go on to do stuff with that resultIsSuccess variable
  }
}

Note the first line in the AfterTest method; I'm using a static reference: TestContext.CurrentContext. The ITest interface doesn't expose the result of the test, so it seems test context is the only way.

Question

And now my question - because NUnit 3.x includes functionality to run tests in parallel, via ParallelizableAttribute - I'm wondering: Is it safe to use that static reference to the current test context? Are there any thread-safety concerns I should be worried about here? Is there a better/more robust way to get the test outcome without resorting to a static reference?

I'm using NUnit framework 3.7.1 in case it matters.

like image 790
Craig Fowler Avatar asked Sep 03 '25 10:09

Craig Fowler


1 Answers

Short answer: Yes.

Mid-size answer: Although it's a static property, we only use it for easy access to the actual context, which is unique for each test.

Explanation: Each use of TestContext.CurrentContext creates a new context, which is not an expensive operation because it's merely a wrapper for TestExecutionContext.CurrentContext. The current execution context is maintained in different ways depending on the platform build of the nunit framework. For desktop .NET we use the CallContext to store it.

like image 130
Charlie Avatar answered Sep 04 '25 22:09

Charlie