Search code examples
c#seleniumtestingnunitxunit

How to pass parameters to the dotnet test command while using NUnit or XUnit


I'm developing some end-to-end tests using C# with .NET Core, Selenium and NUnit. Now i want to write a login testcase. My tests are started from console simply by using the dotnet test command.

I simply want to pass username and password to this command and get them in my tests. I can not use NUnit-Console since it doesn't support .NET Core at the moment.

Whats the suggested way to solve this problem? I would prefer to not store the settings in a file but to directly input them into the console.


Solution

  • If you want to avoid a runsettings file, you can use this workaround. One of the recommended ways of passing parameters, is through environment variables. So in your C# nunit (or xunit) file, you can do something like:

    // in mytest.cs
    var user = Environment.GetEnvironmentVariable("TestUser");
    var password = Environment.GetEnvironmentVariable("TestPassword");
    var url = Environment.GetEnvironmentVariable("TestUrl");
    

    If you do not want to definitively set your environment variables, remember you can always set them temporarily for just your session process. One way of doing this, is by creating a simple cmd file

    #launchtests.cmd
    setlocal
    set TestUser='pete001'
    set TestPassword='secret'
    set TestUrl='http://testserver.local/login'
    dotnet test mytest.csproj
    

    And now the fun part. You can parameterize every aspect of this. So you can change it to:

    #run wity launchtests.cmd pete001 secret 'http://testserver.local/login'
    setlocal
    set TestUser=%1
    set TestPassword=%2
    set TestUrl=%3
    dotnet test mytest.csproj
    

    Or if you want to launch the test from an Azure DevOps (fka VSTS or TFS) pipeline, you can simply use the $(...) notation to inline variables, even if they're marked secret and/or come from Azure KeyVault.

    #In Azure DevOps, variables not marked as secret are already added to the environment
    set TestPassword=$(TestPassword)
    dotnet test $(Build.SourcesDirectory)\MyCompany.MyProduct.UITests\MyTest.csproj --configuration $(BuildConfiguration) --collect "Code Coverage" --logger trx --results-directory $(Agent.TempDirectory)
    

    run Azure DevOps command task