简体   繁体   English

Excel电子表格中的数据驱动的单元测试

[英]Data-Driven Unit Test from Excel Spreadsheet

How do I set up a data-driven unit test method in VS2012 that reads data from an Excel .xlsx spreadsheet? 如何在VS2012中设置一种数据驱动的单元测试方法,该方法从Excel .xlsx电子表格中读取数据?

I have tried Googling the solution but the results are either referring to an older version of Visual Studio or are not for .xlsx files. 我已经尝试使用Google搜索解决方案,但结果要么是指Visual Studio的较早版本,要么不是针对.xlsx文件。

So far I have a test class, test method, and the data source file, TestData.xlsx which is copied to the output directory at build time. 到目前为止,我有一个测试类,测试方法和数据源文件TestData.xlsx,该文件在构建时复制到输出目录。

Figured it out on my own. 我自己弄清楚了。

Give your test method the following attributes: 为您的测试方法提供以下属性:

[DeploymentItem("TestData.xlsx")]
[DataSource("System.Data.Odbc", @"Dsn=Excel Files;dbq=.\TestData.xlsx;defaultdir=.; driverid=790;maxbuffersize=2048;pagetimeout=5", "Sheet1$", DataAccessMethod.Sequential)]
[TestMethod]
public void MyTestMethod()
{
  ...
}

[DeploymentItem] just makes sure that the .xlsx file ends up in the directory where the test ultimately executes from. [DeploymentItem]仅确保.xlsx文件最终位于测试最终执行的目录中。

You also NEED to add the .xlsx file to your project and in it's Properties set the "Copy to Output Directory" property to "Copy if newer" or "Copy always" or else the .xlsx file won't get copied to the test directory and you will get an annoyingly undescriptive error that just says "The Microsoft Access database engine could not find the object 'Sheet1$'." 您还需要将.xlsx文件添加到您的项目中,并在其属性中将“复制到输出目录”属性设置为“如果更新则复制”或“始终复制”,否则.xlsx文件将不会复制到测试中目录,您将得到一个讨厌的,无法描述的错误, 错误仅显示“ Microsoft Access数据库引擎找不到对象'Sheet1 $'。”

"Sheet1$" means that the entire worksheet in the Excel doc named "Sheet1" will be used as the data table. “ Sheet1 $”意味着Excel文档中名为“ Sheet1”的整个工作表将用作数据表。 If you want you can make named ranges in the Excel doc then instead you can put "NamedRangeName" with no "$" sign as your data table source. 如果您希望可以在Excel文档中进行命名范围,则可以将不带“ $”符号的“ NamedRangeName”作为数据表源。

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

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