c# - 使用配置文件指定连接字符串来定义单元测试中的数据源

标签 c# unit-testing

我引用这篇文章来使用 app.config 文件中的连接字符串创建数据驱动的单元测试用例。

https://learn.microsoft.com/en-us/visualstudio/test/walkthrough-using-a-configuration-file-to-define-a-data-source?view=vs-2017

[TestClass]
public class IntegrationTest
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    [DataSource("MySQLDataSource")]
    public void TestRequestSummary()
    {
        string customerId = TestContext.DataRow["MessageId"].ToString();
        Assert.IsNotNull(customerId);
    }
}

应用程序配置

<configuration>
    <configSections>
        <section name="microsoft.visualstudio.testtools" 
                 type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </configSections>
    <connectionStrings>    
        <add name="MySQL" 
             connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MYPortal;Integrated Security=True;" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
    <microsoft.visualstudio.testtools>
        <dataSources>
            <add name="MySQLDataSource" connectionString="MySQL" 
                 dataTableName="ServiceLog" dataAccessMethod="Sequential"/>
        </dataSources>
    </microsoft.visualstudio.testtools>
</configuration>

当我尝试调试测试用例时,它失败并出现以下错误:

Result2 StackTrace:

at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestDataSource.GetData(ITestMethod testMethodInfo, ITestContext testContext)

Result2 Message: The type initializer for 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfiguration' threw an exception.

谁能帮我解决这个问题吗?

环境:

  • Visual Studio 2017
  • Microsoft.VisualStudio.TestTools.UnitTesting
  • .Net 框架 4.6

最佳答案

我使用 MSTest v2 作为我的单元测试框架,他们似乎已经更改了这个特定版本的配置部分。

我在以下线程中找到了答案:

https://github.com/Microsoft/testfx/issues/129#issuecomment-354124544

代码:

将我的 app.config 文件更改为:

<section name="microsoft.visualstudio.testtools"
         type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection,
         Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions"/>

关于c# - 使用配置文件指定连接字符串来定义单元测试中的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54200663/

相关文章:

c# - 两个集合交集

c# - 导航问题 : PopToRootAsync is not supported globally on iOS, 请使用 NavigationPage

c# - 如何以编程方式设置 Windows 音频平衡级别?

javascript - `window` 没有暴露给 Jest

javascript - 如何避免无用的else block 语句来增加单元测试用例中的分支覆盖率?

cocoa - 如何解决 Xcode 4 单元测试中的 "dyld: Library not loaded:"错误?

c# - 在 .NET 中寻找简单的规则引擎库

c# - ServiceStack.Text 可以将 JSON 反序列化为自定义泛型类型吗?

c# - 单元测试中的 DeploymentItem 和 TestCleanup 冲突?

matlab - Matlab 工具箱测试中的 stub