'C# NUnit 3 Data Driven from Excel

Hello I have the following file: testexcel.xlsx > sheet 1

enter image description here

I want to execute this test twice as there are 2 rows with data.

[Test]
[TestCaseSource("Data")]
public void Login(String username, String password)
{
    loginPageModel.DoLogin(username, password);
}

How can I convert that excel data into this kind of data as explained in NUnit 3 official documentation?

static object[] Data = {
        new object[] {username, password}
    };


Solution 1:[1]

You need to read in the Excel file (see Optimal way to Read an Excel file (.xls/.xlsx)) and then return the data from your TestCaseSource. I won't go into reading in the Excel file here because that is covered in the linked question and in many places on the web, but you just need to switch your TestCaseSource to a method and yield return or Select the results.

Don't forget that your TestCaseSource needs to be public static and it is better (but not required) to return TestCaseData instances.

Your code will look something like this.

public static IEnumerable Data()
{
    var rows = ReadExcel("testdata.xlsx");
    return rows.Select(row => new TestCaseData(row[0], row[1]));
}

Solution 2:[2]

If your intention is to separate the test data and code. Please take a look at JsonSectionReader.

This package provides the support for storing the test data in embedded json file, and it has excellent support of deserialization.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Prouse
Solution 2 Nachiappan Kumarappan