在 Excel 数据驱动单元测试中使用数据源相对路径时出错

Error using Data Source relative path in Excel Data Driven Unit Test

我正在使用 System.Data.Odbc 连接字符串连接到 Excel 数据源。使用相对 dbq 路径时出现以下错误:

ERROR [42S02] [Microsoft][ODBC Excel Driver] The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.

App.config:

<configuration>
    <configSections>
        <section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </configSections>
    <connectionStrings>
        <add name="excelConnection" connectionString="Dsn=Excel Files;Dbq=ExcelDataSource.xlsx;Defaultdir=.;driverid=790;maxbuffersize=2048;pagetimeout=5" providerName="System.Data.Odbc"/>
    </connectionStrings>
    <microsoft.visualstudio.testtools>
        <dataSources>
            <add name="excelDataSource" connectionString="excelConnection" dataTableName="Sheet1$" dataAccessMethod="Sequential"/>
        </dataSources>
    </microsoft.visualstudio.testtools>
</configuration>

测试方法属性:

[DeploymentItem("ExcelDataSource.xlsx")]
[DataSource("excelDataSource")]
[TestMethod]

故障排除说明:

问题:defaultDir=.;在哪里?解决?

使用 |DataDirectory| 正确解析变量:defaultDir=|DataDirectory|.

connectionString="Dsn=Excel Files;Dbq=ExcelDataSource.xlsx;Defaultdir=|datadirectory|\;driverid=790;maxbuffersize=2048;pagetimeout=5"

More on the |DataDirectory| variable here