一尘不染

从Excel驱动的C#NUnit 3数据 硒

selenium

我要执行两次此测试,因为有2行数据。

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

如NUnit 3官方文档中所述,如何将excel数据转换为此类数据?
NUnit 3 officialdocumentation?

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

阅读 368

收藏
2020-06-26

共1个答案

一尘不染

我所做的是以下内容,它正在工作

我有测试:

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

通过调用类ExcelReader中的readExcelData()方法来读取Excel文件的类ExcelDataParser

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

这是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;
        }
    }
2020-06-26