Shaggy
Shaggy

Reputation: 5790

Use configuration file to specify connection string to define a data source in unit test

I am referring to this article for creating data-driven unit test cases using a connection string in app.config file.

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);
    }
}

App.config

<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>

When I am trying to debug the test case it failed with the following error:

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.

Could anyone help me solve this?

Environment:

Upvotes: 2

Views: 897

Answers (1)

Shaggy
Shaggy

Reputation: 5790

I was using MSTest v2 as my unit testing framework and it appears to be they have changed the configuration section for this particular version.

I found the answer in following thread:

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

Code:

Changed my app.config file to:

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

Upvotes: 2

Related Questions