【问题标题】:TestInitialize and TestCleanup not running before and after each DataRow of a DataTestMethodTestInitialize 和 TestCleanup 在 DataTestMethod 的每个 DataRow 之前和之后没有运行
【发布时间】:2013-03-22 21:06:12
【问题描述】:

您可以在下面看到一些使用 Mstest 在 Window Phone 单元测试应用程序中编写的代码。
我有一个名为 TestMethod1 的普通 TestMethod,以及一个名为 TestMethod2 的 DataTestMethod,它有三个 DataRows:

[TestClass]
public class UnitTest1
{
    [TestInitialize]
    public void Setup()
    {
        Debug.WriteLine("TestInitialize");
    }

    [TestMethod]
    public void TestMethod1()
    {
        Debug.WriteLine("TestMethod1");
    }

    [DataTestMethod]
    [DataRow("a")]
    [DataRow("b")]
    [DataRow("c")]
    public void TestMethod2(string param)
    {
        Debug.WriteLine("TestMethod2 param=" + param);
    }

    [TestCleanup]
    public void TearDown()
    {
        Debug.WriteLine("TestCleanup");
    }
}

如果我在调试模式下运行测试(Visual Studio 中的 Ctrl+R、Ctrl+T),我会在输出面板中看到:

测试初始化​​
TestMethod1
TestCleanup
TestInitialize
TestMethod2 参数=c
TestMethod2 参数=a
TestMethod2 参数=b
TestCleanup

如您所见,TestInitialize 只执行了两次:一次在 TestMethod1 之前,一次在 TestMethod2 之前,参数为 c。
TestCleanup 也是如此,在 TestMethod1 之后执行一次,最后执行一次。

我希望在每次测试之前和之后执行 TestInitialize 和 TestCleanup,无论它是 TestMethod 还是 DataTestMethod。否则一个测试的执行会影响下一个测试。

我希望它是这样的:

测试初始化​​
TestMethod1
TestCleanup
TestInitialize
TestMethod2 参数=c
TestCleanup
TestInitialize
TestMethod2 参数=a
TestCleanup
TestInitialize
TestMethod2 参数=b
TestCleanup

我没有发现其他人有同样的问题,我做错了什么?

【问题讨论】:

  • 有时人们正在寻找的答案已经在问题中。 +1,清理方法必须是public :D thanx

标签: c# unit-testing windows-phone-8 windows-phone vs-unit-testing-framework


【解决方案1】:

我对此有点陌生,但我认为如果你用[TestMethod] 属性标记[DataTestMethod],它应该为每个测试方法运行初始化和清理。

[TestMethod]
[DataTestMethod]
[DataRow("a")]
[DataRow("b")]
[DataRow("c")]
public void TestMethod2(string param)
{
    Debug.WriteLine("TestMethod2 param=" + param);
}

更新: 微软表示:TestCleanupAttribute“将在标有 TestMethodAttribute 的方法之后运行……”

当我对此进行测试时,它确实有效。当您说它不起作用时,请提供更多详细信息。

如果您希望每个测试类只运行一次初始化程序,您可以使用属性 TestClass Attribute。 See this post.

// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext) { }

// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup() { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2014-05-02
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多