it’s quite frustrating getting a data-driven test running with Visual Studio 2012 and MSTest.

Here is a working sample using a XML-File as datasource for the data-driven test.

Now i’m feeling better 🙂

Sample of the working unit-test

XML-File:

<?xml version="1.0" encoding="utf-8" ?>
<Rows>
  <Row>
    <Country></Country>
    <Image>unknown.gif</Image>
  </Row>
  <Row>
    <Country>germany</Country>
    <Image>germany.gif</Image>
  </Row>
  <Row>
    <Country>usa</Country>
    <Image>usa.gif</Image>
  </Row>
  <Row>
    <Country>some country</Country>
    <Image>unknown.gif</Image>
  </Row>
</Rows>

Unit Test:

[TestClass]
public class CountryHandlerTest
{
    private TestContext testContextInstance;
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }
 
 
    [TestMethod]
    [DeploymentItem("BusinessLogic.Test\\TestData\\GetImageForCountry.xml")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\GetImageForCountry.xml", "Row", DataAccessMethod.Sequential)]
    public void GetImageForCountry_SeveralTests()
    {
        // Get data out of the XML File
        string country = testContextInstance.DataRow["Country"].ToString();
        string image = testContextInstance.DataRow["Image"].ToString();
 
        Execute_GetImageForCountry_SeveralTests(country, image);
    }
 
    /// <summary>
    /// Helper Method that executes the test
    /// </summary>
    /// <param name="country">
    /// <param name="image">
    private void Execute_GetImageForCountry_SeveralTests(string country, string image)
    {
        #region Arrange
 
        string expected = image;
        CountryHandler target = new CountryHandler();
 
        #endregion
 
        #region Act
 
        string actual = target.GetImageForCountry(country);
 
        #endregion
 
        #region Assert
 
        Assert.AreEqual(expected, actual);
 
        #endregion
    }
}

Method that will be tested:

public class CountryHandler
{
    /// <summary>
    /// Get the Image for a given country
    /// </summary>
    /// <remarks>
    /// The following requirements must be fulfilled:
    /// <list type="bullet">
    /// <item>"germany" return "germany.gif"</item>
    /// <item>"usa" return "usa.gif"</item>
    /// <item>all other countries return "unknown.gif"</item>
    /// </list>
    /// </remarks>
    /// <param name="country">
    /// <returns></returns>
    public string GetImageForCountry(string country)
    {
        if (country == "germany")
        {
            return "germany.gif";
        }
        if (country == "usa")
        {
            return "usa.gif";
        }
 
        return "unknown.gif";
    }
}

Runnning the test gives me a nice code coverage 😉
MSTestRowTest_CodeCoverage

Related Resources

Further Reading