Data-Driven Unit Test from Excel Spreadsheet

坚强是说给别人听的谎言 提交于 2020-01-22 00:24:37

问题


How do I set up a data-driven unit test method in VS2012 that reads data from an Excel .xlsx spreadsheet?

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.

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.


回答1:


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.

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$'."

"Sheet1$" means that the entire worksheet in the Excel doc named "Sheet1" will be used as the data table. 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.



来源:https://stackoverflow.com/questions/22538340/data-driven-unit-test-from-excel-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!