Vstest: MSTest: Constructor runs for every test (rather than once for the class) during Debug

Created on 20 Jan 2017  路  6Comments  路  Source: microsoft/vstest

_From @MarkMichaelis on January 16, 2017 21:14_

If you Debug an MSTest with one or more test methods, the constructor runs once for every test (rather than once for the entire class). This does not seem to occur when running (not debugging). The following code demonstrates the issue - failing when debugging (successful when not debugging):

`using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
[TestClass]
public class TestBase
{

}

[TestClass]
public class UnitTestSample
{
    static public int ConstructorCount { get; set; }

    public UnitTestSample()
    {
        ConstructorCount++;
    }

    [TestMethod]
    public void TestMethod1()
    {
    }

    [TestMethod]
    public void TestMethod2()
    {
    }

    [ClassCleanup]
    static public void ClassCleanup()
    {
        Assert.AreEqual<int>(1, ConstructorCount);
    }
}

}
`
@jinujoseph @GrantErickson @morrisjoe

_Copied from original issue: dotnet/roslyn-project-system#1192_

external testfx

All 6 comments

_From @srivatsn on January 16, 2017 21:21_

@dotnet/vstest can you take a look?

That is a non-public repro.

MSTest creates a new instance of the test class for every test method by-design. On 1.1.11 Framework and Adapter both Run and Debug behave similarly. Trying to justify this behavior: This helps isolate test methods without the need of an initialize and cleanup. Changing this behavior would cause a breaking change from legacy. Hence leaving this as is.

I have issue with [CodedUITest], How can I apply fix in my test solutions

@AbhitejJohn

MSTest creates a new instance of the test class for every test method by-design. On 1.1.11 Framework and Adapter both Run and Debug behave similarly. Trying to justify this behavior: This helps isolate test methods without the need of an initialize and cleanup. Changing this behavior would cause a breaking change from legacy. Hence leaving this as is.

Could you then please remove TestInitialize and TestCleanup attributes and instructs users to use ctor/Dispose instead.
How many would you guess have mistakenly optimized their test by moving common setup to ctor to no avail?

Was this page helpful?
0 / 5 - 0 ratings