如何使用C#从电子表格运行Nunit测试用例

时间:2015-06-03 14:09:21

标签: c# c#-4.0 selenium-webdriver c#-3.0 c#-2.0

假设我有电子表格,一列提到了类名,第二列提到了NunitTestcases,三列提到了状态(是或否)

我的场景需要运行标记为“是”的测试用例。(例如,我有10个测试用例,我只需要运行4个测试用例)。

任何人都可以帮助我或提供代码示例。

1 个答案:

答案 0 :(得分:0)

发布的问题与Selenium-Webdriver无关。您想基于读取excel文件来调用方法。虽然这是可以实现的,但却有许多相关内容。为了实现这一点,您应该能够读取excel工作表/文件并检查标志Status,如果是,则需要使用基于类和方法的反射来调用该方法。

       string testAssemblyPath = "Assembly Path"; // Make sure only path and do not specify the assembly name.

        using (ExcelPackage p = new ExcelPackage())
        {
            using (FileStream stream = new FileStream(@"ExcelFilePath.xlsx", FileMode.Open))
            {
                p.Load(stream);

                ExcelWorksheet ws = p.Workbook.Worksheets["Sheet1"];
                int rowIndex = 2;

                for (int index = 0; index < ws.Dimension.Rows - 1; index++)
                {
                    if ("Yes" == ws.Cells[rowIndex + index, 3].Value.ToString())
                    {
                        string className = ws.Cells[rowIndex + index, 1].Value.ToString();
                        string methodName = ws.Cells[rowIndex + index, 2].Value.ToString();

                        Assembly assembly = Assembly.LoadFrom(testAssemblyPath + "TestAssembly.dll");
                        Type type = assembly.GetType(string.Concat(assembly.FullName.Split(',')[0], className));
                        if (type != null)
                        {
                            MethodInfo methodInfo = type.GetMethod(methodName);
                            if (methodInfo != null)
                            {                                    
                                object classInstance = Activator.CreateInstance(type, null);

                                methodInfo.Invoke(classInstance, null);
                            }
                        }
                    }

                }
            }
        }

上面的代码仅显示我们如何调用方法,该方法是测试程序集的一部分(假设测试方法在测试程序集中)。为了阅读excel,我使用了 EPPlus