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:
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:
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!