从Excel驱动的C#NUnit 3数据
你好,我有以下文件:testexcel.xlsx>表1
我想要执行这个testing两次,因为有两行数据。
[Test] [TestCaseSource("Data")] public void Login(String username, String password) { loginPageModel.DoLogin(username, password); }
如何将excel数据转换成NUnit 3官方文档中解释的这种数据?
static object[] Data = { new object[] {username, password} };
我所做的是以下,它的工作
我有testing:
[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; } }
您需要阅读Excel文件(请参阅读取Excel文件(.xls / .xlsx)的最佳方式 ),然后从TestCaseSource
返回数据。 我不会在这里阅读Excel文件,因为这是链接的问题,并在网上的许多地方,但你只需要切换到一个方法和yield return
或Select
结果的TestCaseSource
。
不要忘记,您的TestCaseSource
需要是public static
,返回TestCaseData
实例会更好(但不是必须的)。
你的代码看起来像这样。
public static IEnumerable Data() { var rows = ReadExcel("testdata.xlsx"); return rows.Select(row => new TestCaseData(row[0], row[1])); }