C# NUnit 3 Data Driven from Excel

前端 未结 3 1552
深忆病人
深忆病人 2021-01-16 17:44

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

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

[Test]
[TestCase         


        
3条回答
  •  余生分开走
    2021-01-16 18:13

    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]));
    }
    

提交回复
热议问题