Pass test case parameters using nunit console

I develop tests using Nunit and a data validation method . I have a test method with two parameters: the path to the xlsx file and the name of the worksheet. It works fine in Visual Studio when I pass parameters in the TestCase attribute, for example, when I want to run 3 test cases, I need 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 the Nunit Console (so as not to write the parameters in the code).

Can this be achieved?

+8
c # nunit data-driven-tests nunit-console
source share
2 answers

If you are using NUnit 3, you can use the 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 
+19
source share

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 a 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 the test cases that I want to run (file paths and worksheet names) in a csv file. This may not be the best solution, but I have achieved my goal of not writing parameters in code.

+3
source share

All Articles