Write Test Progress To The Console With NUnit

NUnit: writing test progress to the console

I recently needed to write test progress to the console with NUnit. The task we want to solve here is basically the TODO part of this snippet:

[TestFixture]
public class MyTests
{
[Test]
public void SampleTest()
{
// some operations here, like starting a server for tests in-memory…
// TODO: inform the 'user' (the one who runs the test) that the server is already running
while (true)
{
// keep it running on purpose (e.g. for E2E tests)
}
}
}

The title picture of this article shows the end result. If you want to know the solution, keep reading 🙂

Context

The context of this need is very simple. I have a unit test in which I want to perform some operations and keep the test running indefinitely afterwards. The use case might be instantiation of an in-memory test server. After that, I want to inform the user (programmer or the one running the test) that the server is up and running. I want to do that before the test finishes. In other words: I want to write the test’s output while it’s still running.

In my case, I was running two .NET Core apps in-memory. The backend server app and the ASP.NET Core web application. In the process, the web app got its IP address assigned dynamically. Meaning that the IP was different with each test run. This particular test was used to run the app in-memory and let the user manually use the application. It means the user must know the IP/URL of the in-memory web app. That’s why I needed to output the dynamic IP address into the NUnit test output 😉

Solution

The solution to write test progress to the console with NUnit is very simple. To do that, use TestContext.Progress.WriteLine(string) method from NUnit.Framework namespace:

[TestFixture]
public class MyTests
{
[Test]
public void SampleTest()
{
// some operations here, like starting a server for tests in-memory…
TestContext.Progress.WriteLine("The server is running now! You can reach it on https://localhost:8067/");
while (true)
{
// keep it running on purpose (e.g. for E2E tests)
}
}
}

And that’s it! I’m publishing this simple solution, because it took me some time to find 🙂

I previously tried with TestContext.Out.WriteLine, System.Diagnostics.Trace.WriteLine and System.Console.WriteLine, but all of them output the text after the test finishes.

Finally, you can also run the test from cmd using dotnet test:

Hope it’s useful!

.NET full stack web developer & digital nomad
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments