5

我有一个调用 2 个子测试方法的测试方法。这两个子方法都是从 XML 文件中驱动的数据。如果我运行每个子方法,它们运行良好且成功。但是,当我运行主测试方法(两个子方法的调用者)时,它发现 TestContext.DataConnection 和 TestContext.DataRow 为空。

    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  
    }

如果我全部运行,则 2 个方法通过,1 个失败。如果我单独运行, SaveData_Json_LocalStorage 不会通过,总是将 TestContext.DataRow 设为 null。里面调用多个方法可以吗。编写链式测试用例的最佳方法是什么。

4

1 回答 1

2

仅当必须具有不可重新创建的数据时才应进行链接。否则,使每个测试成为不同的测试。

从 XML 文件驱动的数据。

考虑将只读Xml 放入在方法中测试之前运行一次ClassInitialization的属性中。然后测试各个操作,然后是“主要”操作,每个操作都作为一个单独的可测试单元。

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

否则,请根据正在执行的测试或是否来自特定调用来模拟数据,那么 ashim呢?请参阅我的文章Shim 在棘手的单元测试情况中拯救了一天

于 2015-05-18T20:41:56.583 回答