16

I am developing tests using Nunit and data driven testing approach. I have test method with 2 parameters: path to xlsx file and worksheet name. It works perfect in Visual Studio when I pass parameters in TestCase attribute, for example when I want to run 3 test cases have to write something like this:

[TestCase(@"pathToFile.xlsx", "TestCase1")]
[TestCase(@"pathToFile.xlsx", "TestCase2")]
[TestCase(@"pathToFile.xlsx", "TestCase3")]
public void performActionsByWorksheet(string excelFilePath, string worksheetName)
{    
    //test code
}

I would like to run my test cases and pass parameters using Nunit Console (not to write parameters in code).

Is it possible to achieve it?

kotoj
  • 759
  • 1
  • 6
  • 25

2 Answers2

34

If you are using NUnit 3 you can use TestContext.Parameters property:

[Test]
public void performActionsByWorksheet()
{
    string excelFilePath = TestContext.Parameters["excelFilePath"];
    string worksheetName = TestContext.Parameters["worksheetName"];
    TestContext.WriteLine(excelFilePath);
    TestContext.WriteLine(worksheetName);
}

and --params command line argument:

nunit3-console.exe path/to/your/test.dll --params=excelFilePath=testPath;worksheetName=testName
Vadim Pashkov
  • 512
  • 6
  • 8
  • Thanks a lot! It works for 1 set of parameters. What about if I want to run more test cases like in my question? – kotoj Sep 29 '16 at 14:01
  • 1
    @kotoj, pass them as delimited string inside one parameter – Fabio Oct 03 '16 at 08:41
  • can you help me in doing this with AutoRun().Execute() . I run test with category attribute as ``.Execute(new String[] { "--where= cat=testname"});`` now how to add `--params` in this? – Dimple Feb 20 '18 at 06:45
  • 2
    As of 3.10 you should switch to --testparam:Key=Value instead --params. This is to avoid issues with semicolumns e.g. in connection strings. – Pavel Donchev May 03 '20 at 14:28
4

I found a workaround for many test cases, using TestCaseSource.
Test code:

[Test, TestCaseSource("testData")]
public void performActionsByWorksheet(string excelFilePath, string worksheetName)
{
    Console.WriteLine("excel filePath: {0}", excelFilePath);
    Console.WriteLine("worksheet Name: {0}", worksheetName);
}

Getting test data from csv file:

static object[] testData()
{
    var reader = new StreamReader(File.OpenRead(@"TestCases.csv"));
    List<object[]> rows = new List<object[]>();

    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        var values = line.Split(',');
        rows.Add(values);
    }

    return rows.ToArray<object[]>();                        
}

and I store all test cases I want to run (file paths and worksheet names) in csv file. Maybe not the best solution, but I achieved my goal - not to write parameters in code.

kotoj
  • 759
  • 1
  • 6
  • 25