简体   繁体   English

如何读取Excel列中的每一行以进行数据驱动的单元测试

[英]How to read every row in a column in Excel for a data driven unit test

I've setup data driven unit tests in my solution. 我已经在解决方案中设置了数据驱动的单元测试。 It's wired up, everything is working fine, which is what most of the articles and questions online seem to be focused around. 它已连接好,一切工作正常,这是大多数在线文章和问题似乎都围绕的内容。

What I cannot find is how I read subsequent rows after the first row in any given column. 我找不到的是如何读取任何给定列中第一行之后的后续行。

For example if my excel document is setup like so: 例如,如果我的excel文档设置如下:

  A    |   B
------ | ------
  A1   |   B1
  A2   |   B2
  A3   |
  A4   |  

Then back in my unit test I do something like: 然后回到我的单元测试,我做类似的事情:

var getValue = TestContext.DataRow["A"];
var getOtherValue = TestContext.DataRow["B"];

The output is that getValue = "A1" and getOtherValue = B1 . 输出是getValue = "A1"getOtherValue = B1 If I try to do something like this instead: 如果我尝试做这样的事情:

var getValue = TestContext.DataRow[0];
var getOtherValue = TestContext.DataRow[1];

The outputs are still exactly the same, which makes sense. 输出仍然完全相同,这很有意义。

What I am confused with is how to get the value in A2 , A3 , B2 , and so on. 我感到困惑的是如何获取A2A3B2等中的值。 That way I can test all of the different scenarios by just plugging them into excel. 这样,通过将它们插入excel,我可以测试所有不同的情况。

For another example, if I have this table: 再举一个例子,如果我有这个表:

 Cost  |  QtyOrdered 
------ | ------------ 
  10   |   10       
  5    |   null
 null  |   2
 null  |   null       

In the above scenario I would like to run through all of the different rows and make sure that the values plugged in are what I expect. 在上述情况下,我想遍历所有不同的行,并确保插入的值是我期望的值。 The first row I would expect 100 , and in every extra row I would expect an error message in my unit test. 我希望第一行为100 ,而每增加一行,我就会在单元测试中看到一条错误消息。

I don't really see the point of data driven unit tests in excel if I can't just plug in a bunch of data in for multiple rows for each column. 如果我不能只为每列插入多行数据,我真的看不到Excel中数据驱动单元测试的意义。

You can import the data from your Excel sheet and run your tests over the resultant data set using loops or any mechanisms that suit your needs. 您可以使用循环或任何适合您需要的机制,从Excel工作表中导入数据并在结果数据集上运行测试。 I personally prefer ClosedXml because of it's usability and speed. 我个人更喜欢ClosedXml,因为它的可用性和速度。 Alternatively, you can use the native Microsoft OLEDB library to get it done. 或者,您可以使用本机Microsoft OLEDB库来完成它。 Good luck! 祝好运!

Doing data driven unit tests like this will call your method one time for every row in your spreadsheet. 进行这样的数据驱动的单元测试将针对电子表格中的每一行一次调用您的方法。 If you have everything wired up properly then there is no need for anything else. 如果一切都正确连接,则不需要其他任何东西。

I'll leave this question up since I feel like it could be useful to someone else in the future since it wasn't immediately apparent how this worked. 我将这个问题搁置一旁,因为我觉得它将来可能对其他人有用,因为现在尚不清楚它是如何工作的。

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

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