visual-studiounit-testingmstestvs-unit-testing-framework

Should I initialize each test method, or just the class, or neither?


The question I pose to myself (and now to the entire world, and perhaps beyond), is in my comment below:

[TestMethod()]
public void SetMessageTypeSubcodeTest()
{
    int AMessageTypeSubcode;
    // Should I put this class instantiation in MyTestInitialize?
    MessageClass target = new MessageClass(); 
. . .

Should I do this:

[TestInitialize()]
public void MyTestInitialize()
{
MessageClass target = new MessageClass(); 
}

...or this:

[ClassInitialize()]
public void MyTestInitialize()
{
MessageClass target = new MessageClass(); 
}

...or neither?

And since C#/.NET is garbage collected, there's no need to free MessageClass in the TestCleanup() or ClassCleanup() method, is there?


Solution

  • You want brand new instance of class you're testing for every single test in your set. This will prevent any possible side effects (which may happen), and as a result tests (which should be units, separated) influencing one another.