简体   繁体   English

使用带有Nunit的Excel数据源进行单元测试

[英]Unit Testing With Excel Data Source with Nunit

I need to test some classes with Nunit by importing data from excel data source in C#,I couldn't find any helpful resource to guide me ,Is there any solution? 我需要通过从C#中的excel数据源导入数据来使用Nunit测试某些类,我找不到任何有用的资源来指导我,是否有解决方案? Consider this test in Nunit 考虑在Nunit中进行此测试

[Test]
[TestCase(new[] { -4, -3, -3, -2, -1, 0, 1, 2, 2, 3, 4 }, 
          new []{1, 0, 1, 0,1, 0, 1, 1, 0, 1, 0})]
public void YourTest(int[] given, int[] expected)  
{ 
///some code
} 

I would read data from excel, If I have one excel files I put the given Values in first column and expected values in second column: 我将从excel中读取数据,如果我有一个excel文件,则将给定的值放在第一栏中,将期望的值放在第二栏中:

column1(in Excel)  column2(in Excel)
-4                      1
-3                      0
-3                      1
-2                      0
-1                      1
0                       0
1                       1
2                       1 
2                       0
3                       1
4                       0

The reason I want to test with excel because I need to apply some formula on column1 and my formula results appers on column2 and I don't like to copy from excel to my test class. 之所以要使用excel测试,是因为我需要在column1上应用一些公式,而公式结果应用于column2,并且我不喜欢从excel复制到测试类。

In MsTest we have : 在MsTest中,我们有:

[TestMethod]
  [Owner("Name")]
  [TestProperty("TestCategory", "Developer"),
      DataSource("Microsoft.ACE.OLEDB.12.0",
     "Data Source=C:/Sheets/DataSheet.xlsx;Extended Properties=Excel 12.0;",
     "[Sheet1$]",
     DataAccessMethod.Sequential)]

Do we have the same thing in Nunit ,Or we need to simulate ? Nunit中是否有相同的东西,还是需要模拟? How we can simpuate it ? 我们该如何模拟呢? In [Setup] section or in [TestMethod] 在[设置]部分或[测试方法]中

If your question is "how do I read data from Excel" and you don't care about formatting (ie you only want the data) then your best bet is probably OleDb. 如果您的问题是“我如何从Excel中读取数据”,而您不关心格式(即,您只想要数据),那么最好的选择就是OleDb。 It's about the quickest and easiest way to code data retrieval from Excel. 它是从Excel检索数据的最快,最简单的方法。

Have a look here for a quick tutorial. 在这里查看快速教程。 It should give you everything you need. 它应该为您提供所需的一切。

Once you have an idea of how it works, if you run into any trouble then there are plenty of answers on this site to help you out. 一旦了解了它的工作原理,如果遇到任何麻烦,那么此站点上将有很多答案可以帮助您。

Use EPPlus and you can easily read excel files, something like this : 使用EPPlus ,您可以轻松读取excel文件,如下所示:

var ep = new ExcelPackage(new FileInfo("c:\\path-to-excel\\data.xslx"));
ExcelWorksheet ws = ep.Workbook.Worksheets["Sheet1"];

// first row is column name, array indexer goes from 1 
for (int i = 2; i < ws.Dimension.End.Row; i++)
{
  int given = (int)ws.Cells[i, 1].Value;
  int expected = (int)ws.Cells[i, 2].Value;
  YourTest(given, expected);
}

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

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