-->

Pass parameters via the command line to NUnit

2020-02-08 10:05发布

问题:

Is it somehow possible to pass values to NUnit tests via the command line?

My tests use a certain URL. I have different instances of my code at different URLs and would like to specify the URL via the command line. File App.config is not an option, because I want to run the tests for different URLs via a batch file.

回答1:

Use an environment variable to pass the information.

Use set from the command-line or <setenv> from NAnt. Then read the value using Environment.GetEnvironmentVariable().



回答2:

There seems to be no solution at the moment. The best option is to use NUnit project files, modify settings there and pass the solution file to the runner.



回答3:

I had a similar issue. The answer of Achim put me on the right track, and for other readers:

Create a file, like example.nunit, like this:

<NUnitProject>
  <Settings activeconfig="local"/>
  <Config name="local" configfile="App.config">
    <assembly path="bin\Debug\example.dll"/>
  </Config>
  <Config name="dev" configfile="App.Dev.config">
    <assembly path="bin\Debug\\example.dll"/>
  </Config>
  <Config name="test" configfile="App.Test.config">
    <assembly path="bin\Debug\\example.dll"/>
  </Config>
</NUnitProject>

All the file / paths (of the configuration and assembly files) are relative to the location of the NUnit file. Also the App.config, App.Dev.config, etc. file are just .NET configuration files.

Next when you want to run it for a certain configuration you execute it like this:

nunit3-console.exe example.nunit /config:test

More information about the format of the NUnit file is in NUnit Project XML Format.

More information about command-line arguments is in http://www.nunit.org/index.php?p=consoleCommandLine&r=2.2.5



回答4:

NUnit 3 now allows passing parameters. Here is the usage

nunit3-console [inputfiles] --params:Key=Value

From the documentation

--params|p=PARAMETER

A test PARAMETER specified in the form NAME=VALUE for consumption by tests. Multiple parameters may be specified, separated by semicolons or by repeating the --params option multiple times. Case-sensitive.

Here's how you can access the parameter through code:

var value= TestContext.Parameters.Get("Key", "DefaultValue");