Using TestRunParameters in your NUnit tests using .runsettings

Using TestRunParameters in your NUnit tests using .runsettings

I've been getting a lot of traffic lately related to the google search phrase "nunit runsettings example" which at the moment leads to this blogpost I wrote on how to use Playwright with NUnit, which doesn't really cover how to set up .runsettings but rather how you can toggle headless mode in Playwright (totally different topic).

So I thought I would share a little tutorial on how you can set up a new NUnit project and use .runsettings and TestRunParameters in your tests.

We'll start from scratch and set up a new project, if you alreay have an NUnit test project created you can jump to step 3.

Setup a new NUnit Test Project:

1. Create a new NUnit Test Project in Visual Studio:

2. Select Framework .NET 6.0 (Long-term support):

Add a .runnsettings file to your solution:

3. Add a file to your solution named .runsettings and add this xml:
<?xml version="1.0" encoding="utf-8"?>
    <RunSettings>
        <TestRunParameters>
        <Parameter name="someParameterName" value="someExampleValue" />
    </TestRunParameters>
</RunSettings>

4. Add a simple test to verify that your tests can find your .runsettings and access the parameters:


Bonus step: I usually try not having magic strings with parameter names spread across my projects but instead gather them all in a shared constant class so that I may access and modify them from one shared source. Using this approach my test parameter would be accessed with something like this:

 

5. Run your tests! ✅
That's it! Hopefully you're able to access your test parameters in the example test and your test should be green.

Having problems?


Your .runsettings should be automatically picked up based on the name of the file, however there are a few common mistakes that can lead to Visual Studio not finding your .runsettings that you need to watch out for:

1. Make sure autodetection of runsettings in enabled in Visual Studio by checking this checkbox: Tools > Options > Test > Auto Detect runsettings Files.

2. Make sure you have created your runsettings file in the root of your solution, not your project root.

3. If all else fails and your tests still can't find your .runsettings file, you can specify the file manually in the Test Explorer by selecting Options > Configure Run Settings > Select solution wide Run Settings file.

For a deeper understanding of .runsettings and more configuration visit the Microsoft Documentation on this tropic.

Hope you enjoyed it. Take care of each other!

Cheers friends! ❤️