Search code examples
c#nunitnunit-3.0nunit-console

Selecting tests by parameter in NUnit 3 console


I have tests parameterized with ValueSource attribute. The source provides 3 parameters (these are environments to run the test in) and I can see and select them in Test Explorer in Visual Studio. But how do I select specific parameters when using NUnit console runner? I tried --params environmentId:prod, but it does not work (tests for all three environments are executed).

P.S: environmentId is my test method's parameter name and "prod" is one of three values provided with ValueSource attribute.


Solution

  • There's a bit of misunderstanding implied in the question regarding the --params option. It doesn't select tests but passes information to the tests, which may be accessed using the TestContext. And it has no connection at all with the parameters of test cases that take arguments.

    You have two ways to go here: (1) figure out the right way to select the test cases from the command-line as you are currently trying to do or (2) actually use the --params option in the intended way. Note that these are mutually exclusive options.

    1. Selecting the correct cases.

      Every test case has a name, which includes the arguments. You can select the correct cases using an expression that indentifies the ones you want and eliminates the ones you don't want. For example, the option --where "test==Your.Name.Space.YourMethod" would select all the cases for a given method. To select those cases with just the "prod" option, you might use a regular expression... perhaps something like --where "test=~/Your\.Name\.Space\.YourMethod\(prod/ assuming the argument in question is the first one. Obviously, this is not an easy command-line to type, so the second option may look better to you.

    2. Using --params correctly

      Based on the name of the environmentID parameter, I'm guessing you might want to run all your tests using the same value rather than changing it in the course of a test run. That's the purpose of run parameters as passed to your application by the --params option. Using --params:environmentID=prod sets up the test run so that any tests needing the correct environmentID can easily access it. You would no longer use environmentID as a C# parameter to your test method but would access the value in the body of the test with code like

      string environmentID = TestContext.Parameters.Get("environmentID");

      You may also provide a second argument to Get, specifying the environment to use if no parameter is passed.

    Hopefully, one of these two approaches will work for you!