Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test TestContext Multiple calls

I have a Test Method which is calling 2 Sub Test Methods. Both the sub Methods are Data Driven from an XML file. If I run each sub methods they run fine and successful. However, when I run Main Test Method (caller of both sub methods) it finds TestContext.DataConnection and TestContext.DataRow as null.

    private TestContext testContext;
    public TestContext TestContext
    {
        get { return testContext; }
        set { testContext = value; }
    }
    [TestMethod]
    public void SaveEmpty_Json_LocalStorage()
    {
        // Testing JSON Type format export and save
         SetWindowsUsers();
        // Add Network Information
        SetWifiInformation();

        // More logic and assertions here.
        // More logic and assertions here.
        // More logic and assertions here.
    }

    [TestMethod]
    [DeploymentItem("input.xml")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
               "input.xml",
               "User",
                DataAccessMethod.Sequential)]
    public void SetWindowsUsers()
    {
      Console.WriteLine(TestContext.DataRow["UserName"].ToString())
      // MORE LOGIC and Asserts  
    }

    [TestMethod]
    [DeploymentItem("input.xml")]
    [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
               "input.xml",
               "WifiList",
                DataAccessMethod.Sequential)]
    public void SetWifiInformation()
    {
      Console.WriteLine(TestContext.DataRow["SSID"].ToString())
      // MORE LOGIC and Asserts  
    }

If I Run All, 2 Methods pass and 1 fails. If I run individually, SaveData_Json_LocalStorage Does not pass, always gets TestContext.DataRow as null. Is it okay to call multiple methods inside. What is best way of writing chained test cases.

like image 344
rocky Avatar asked Nov 01 '22 03:11

rocky


1 Answers

Chaining should only be done if one has to have non-recreate-able data. Otherwise make each test a distinct test.

Data Driven from an XML file.

Consider placing the read-only Xml into a property which is run once before thet tests in the ClassInitialization method. Then test the individual operations, followed by the "Main" operation, Each as a separate testable unit.

public static XDocument Xml { get; set; }

[DeploymentItem("input.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
           "input.xml",
           "User",
            DataAccessMethod.Sequential)]
[ClassInitialize()]
public static void ClassInit(TestContext context)
{ // This is done only once and used by other tests.
    Xml = ...
    Assert.IsTrue(Xml.Node ... );
}

Otherwise look into mocking the data depending on the test being performed or if it comes from a specific call, how about a shim? See my article Shim Saves The Day in A Tricky Unit Test Situation.

like image 111
ΩmegaMan Avatar answered Nov 08 '22 08:11

ΩmegaMan