10

Below you can see some code written with Mstest in a Window Phone Unit Test App.
I have a normal TestMethod called TestMethod1, and a DataTestMethod called TestMethod2 which has three 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");
    }
}

If I run the tests in debug mode (Ctrl+R,Ctrl+T in Visual Studio) I see this in the output panel:

TestInitialize
TestMethod1
TestCleanup
TestInitialize
TestMethod2 param=c
TestMethod2 param=a
TestMethod2 param=b
TestCleanup

As you can see, TestInitialize was executed only twice: once before TestMethod1 and once before TestMethod2 with param c.
It's the same for TestCleanup, which was executed once after TestMethod1 and once at the very end.

I would expect the TestInitialize and TestCleanup to be executed before and after each test, no matter if it's a TestMethod or a DataTestMethod. Otherwise the execution of one test can influence the next one.

I expected it to be like this:

TestInitialize
TestMethod1
TestCleanup
TestInitialize
TestMethod2 param=c
TestCleanup
TestInitialize
TestMethod2 param=a
TestCleanup
TestInitialize
TestMethod2 param=b
TestCleanup

I did not find anyone else with the same problem, what am I doing wrong?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
stralsi
  • 988
  • 1
  • 10
  • 17
  • sometime the answer one is looking for is already in the question. +1, the clean up method has to be `public` :D thanx – Mong Zhu Jul 24 '20 at 13:13

1 Answers1

4

I am kind of new to this but I think that ff you mark the [DataTestMethod] with the [TestMethod] attribute as well it should run the Initialize and Cleanup for each Test Method.

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

Update: Microsoft says: TestCleanupAttribute "will be run after methods marked with the TestMethodAttribute ..."

When I test this it does work. Please provide further details when you say it doesn't work.

If you wish initializers that run only once per Test Class you can use the attribute 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() { }
Community
  • 1
  • 1
CaptainBli
  • 4,121
  • 4
  • 39
  • 58