skip to content

In NUnit 5, what are TestContext.Out, TestContext.Progress and TestContext.CurrentContext for, especially when tests run in parallel?

level: juniorimportance: should knowfreq 30%

answer

  1. output attached to the running test
  2. immediate progress messages
  3. CurrentContext.Test.Name and Properties
  4. Result.Outcome in [TearDown]
  5. per-test context, not a static

basics

~20 s

TestContext.Out writes to the current test's own output, TestContext.Progress writes immediate progress messages, and TestContext.CurrentContext describes the running test: name, properties, arguments, result. Each follows the test's own execution context, so parallel tests do not mix.

solid answer

~40 s

`TestContext.Out` is a `TextWriter` whose text is stored with the **current test's** result, so diagnostic lines appear under the right test in the report even when several tests run at once. `TestContext.Progress` writes **immediately** (via the error stream), for progress messages you want to see while a long run is still going. `TestContext.CurrentContext` returns information about the test that is running on the calling flow: `Test.Name`, `Test.FullName`, `Test.Arguments`, `Test.Properties` (values from `[Property]` and `[Category]`), `Result.Outcome` in a `[TearDown]`, `WorkerId`, `TestDirectory` and `Random`. Because it is resolved from the test's execution context, it is correct under parallel execution, unlike a static field holding "the current test". `TestContext.AddTestAttachment` attaches a file, such as a statement PDF, to the result.

code

csharp · 17 lines
csharp
[Parallelizable(ParallelScope.All)]
[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]
public class StatementBuilderTests
{
    [Test]
    [Property("Product", "Savings")]
    public void Monthly_statement_lists_interest()
    {
        var ctx = TestContext.CurrentContext;
        var schema = $"t_{ctx.Test.ID}";              // unique per test
        TestContext.Out.WriteLine($"{ctx.Test.Name} on {ctx.WorkerId}, schema {schema}");
        TestContext.Progress.WriteLine("building statement...");

        var product = ctx.Test.Properties.Get("Product");
        Assert.That(product, Is.EqualTo("Savings"));
    }
}

go deeper

for a junior

Recall the three writers and that TestContext.CurrentContext.Test.Name gives the running test's name.

for a middle

Explain where each writer's text ends up, what CurrentContext exposes, and how a teardown uses Result.Outcome to act on failure.

for a senior

Use per-test context to isolate resources and diagnostics in parallel runs, and replace static 'current test' patterns that break under concurrency.

for a principal

Set the suite's conventions for diagnostics and failure evidence so parallel CI runs produce reports a reviewer can act on.

## Why a test needs context Tests sometimes need to know **which test is running**, to write diagnostics that end up in the right place, or to attach evidence when they fail. NUnit exposes all of this through the static `TestContext` class. Under parallel execution, getting this right is the difference between readable failures and logs interleaved from four tests at once. ## The writers | Member | Where the text goes | Use it for | |---|---|---| | `TestContext.Out` (and `TestContext.WriteLine`) | stored with the **current test's** output | diagnostics to read beside a failure | | `TestContext.Progress` | written **immediately**, through the error stream | "processing statement 40 of 200" during a long run | | `TestContext.Error` | the error stream | error output | `TestContext.Out` resolves to the writer of the test that is running on the current execution context. While four banking tests run on four workers, each test's lines are kept with that test's result, so the report shows them under the right test. NUnit also captures `Console.Out` for the running test, so a `Console.WriteLine` inside a test body usually lands in the same place. `TestContext.Out` states the intent explicitly and is the documented way to write to the test result. ## CurrentContext: describing the running test `TestContext.CurrentContext` returns a fresh view of the test executing on the calling flow. Useful members: - `Test.Name`, `Test.FullName`, `Test.MethodName`, `Test.ClassName` - identify the test, for example to name a per-test temp directory or database schema. - `Test.Arguments` - the arguments of the current parameterised case. - `Test.Properties` - values attached with `[Property("Product", "Savings")]`; categories from `[Category]` appear under the `Category` key. - `Result.Outcome` - read in a `[TearDown]` to act only when the test failed, for example to save logs. - `WorkerId` - the name of the worker thread running the test, handy when investigating a parallel-only failure. - `TestDirectory` and `WorkDirectory` - where the test assembly is and where output files go. - `Random` - a randomizer seeded for each test from the run's seed, so a run's values can be reproduced. - `CancellationToken` - signalled when the test is cancelled, for example by a timeout. ## Why not a static field A common pre-parallel pattern stores "the current test name" in a static field during `[SetUp]`. Under parallelism the next test's `[SetUp]` overwrites it while the first test is still running, so logs and file names point at the wrong test. `TestContext.CurrentContext` is resolved from the **test's own execution context**, which flows with that test across `await` points, so it stays correct per test. ## Evidence on failure ```csharp [TearDown] public void SaveStatementOnFailure() { var ctx = TestContext.CurrentContext; if (ctx.Result.Outcome.Status == TestStatus.Failed) { var path = Path.Combine(ctx.WorkDirectory, $"{ctx.Test.Name}.pdf"); _statement.SaveAs(path); TestContext.AddTestAttachment(path, "Generated statement"); } } ``` `AddTestAttachment` records a file against the current test; it throws `FileNotFoundException` if the path does not exist, so write the file first. ## Which writer to use - Diagnostics that explain a failure: `TestContext.Out`, so they sit beside the failure in the report. - Live status for a long-running test: `TestContext.Progress`. - Files that explain a failure (a statement, a screenshot, a request log): write them under `WorkDirectory` and attach them with `TestContext.AddTestAttachment`. - Anything another test needs to read: none of these; tests should not communicate through output. ## Run parameters `TestContext.Parameters` reads named values passed by the runner (for example a sandbox URL), so a suite can be pointed at a different environment without recompiling. Use `Get` with a default value so the tests still run locally. ## Pitfalls 1. Writing progress with `TestContext.Out` and expecting to see it live: `Out` is attached to the result and appears when the test reports; use `Progress` for live messages. 2. Capturing `TestContext.CurrentContext` in a static or a long-lived singleton and reading it later from another test. 3. Writing from a background thread started without the test's execution context; that output may not be attributed to the test. 4. Using the test name directly as a file name without considering characters from parameterised arguments.

  • Why is TestContext.Progress better than TestContext.Out for a long-running NUnit test's status messages?
    `TestContext.Out` text is stored with the test's result and is shown when the test reports, after it finishes. `TestContext.Progress` writes immediately through the error stream, so status lines appear while the run is still in progress.
  • How do you read a [Property] value from inside an NUnit test?
    Use `TestContext.CurrentContext.Test.Properties.Get("Product")`, which returns the first value for that key, or the indexer for all values. Categories set with `[Category]` are stored under the `Category` key in the same property bag.
  • How can an NUnit [TearDown] tell whether the test just failed?
    Read `TestContext.CurrentContext.Result.Outcome`. Its `Status` is `TestStatus.Failed` for failures and errors, which lets the teardown save logs or attach files only when they will be needed.

  • TestContext.Out shows its lines live while the test is still running
  • Under parallel runs TestContext.CurrentContext may return a different test's name
  • Storing the test name in a static field in [SetUp] is safe in parallel
  • Categories cannot be read from TestContext properties
  • AddTestAttachment silently ignores a missing file
  • TestContext.Progress output is stored only in the results file