简体   繁体   English

C#NUnit 3从Excel驱动的数据

[英]C# NUnit 3 Data Driven from Excel

Hello I have the following file: testexcel.xlsx > sheet 1 您好我有以下文件:testexcel.xlsx>表1

在此输入图像描述

I want to execute this test twice as there are 2 rows with data. 我想要执行此测试两次,因为有2行数据。

[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 ? 如何在NUnit 3官方文档中解释,将该Excel数据转换为此类数据?

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

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 classe ExcelDataParser通过从ExcelReader类调用方法readExcelData()来读取excel文件

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: 这是ExcelReader类,它包含ReadExcelData方法,该方法将excel文件中的每一行转换为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;
        }
    }

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 . 您需要读取Excel文件(请参阅读取Excel文件的最佳方式(.xls / .xlsx) ),然后从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. 我不会在这里阅读Excel文件,因为链接问题和Web上的许多地方都有这个内容,但您只需要将TestCaseSource切换为方法并yield returnSelect结果。

Don't forget that your TestCaseSource needs to be public static and it is better (but not required) to return TestCaseData instances. 不要忘记您的TestCaseSource需要是public static并且返回TestCaseData实例更好(但不是必需)。

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

If your intention is to separate the test data and code. 如果您打算将测试数据和代码分开。 Please take a look at JsonSectionReader . 请看一下JsonSectionReader

This package provides the support for storing the test data in embedded json file, and it has excellent support of deserialization. 该软件包提供了对嵌入式json文件中存储测试数据的支持,并且它具有出色的反序列化支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM