C# NUnit 3 Data Driven from Excel

梦想与她 提交于 2019-12-19 10:55:10

问题


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

回答1:


What i did is the following and it's working

I have the Test:

[Test TestCaseSource(typeof(ExcelDataParser),"BudgetData") Category("1")]
public void AchterBudget(string min, string max)
{
.....
}

The classe ExcelDataParser which reads the excel file by calling the method readExcelData() from the class ExcelReader

class ExcelDataParser
{
static string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
static string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
static string projectPath = new Uri(actualPath).LocalPath;
static string excelPath = projectPath + @"com.seloger.resources\excelData\";

public static IEnumerable<TestCaseData> BudgetData
{
  get
   {
      List<TestCaseData> testCaseDataList = new ExcelReader().ReadExcelData(excelPath + "AcheterBudgetData.xlsx");

if (testCaseDataList != null)
   foreach (TestCaseData testCaseData in testCaseDataList)
                                yield return testCaseData;
                    }
                }
    }

And this is the class ExcelReader which contains the method ReadExcelData that converts every row from the excel file to a TestCaseData:

class ExcelReader
    {
        public List<TestCaseData> ReadExcelData(string excelFile, string cmdText = "SELECT * FROM [Feuil1$]")
        {
            if (!File.Exists(excelFile))
                throw new Exception(string.Format("File name: {0}", excelFile), new FileNotFoundException());
            string connectionStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES\";", excelFile);
            var ret = new List<TestCaseData>();
            using (var connection = new OleDbConnection(connectionStr))
            {
                connection.Open();
                var command = new OleDbCommand(cmdText, connection);
                var reader = command.ExecuteReader();
                if (reader == null)
                    throw new Exception(string.Format("No data return from file, file name:{0}", excelFile));
                while (reader.Read())
                {
                    var row = new List<string>();
                    var feildCnt = reader.FieldCount;
                    for (var i = 0; i < feildCnt; i++)
                        row.Add(reader.GetValue(i).ToString());
                    ret.Add(new TestCaseData(row.ToArray()));
                }
            }
            return ret;
        }
    }



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/44260816/c-sharp-nunit-3-data-driven-from-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!