Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
B. Clay Shannon-B. Crow Raven Avatar asked Oct 16 '25 13:10

B. Clay Shannon-B. Crow Raven


2 Answers

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.

like image 142
k.m Avatar answered Oct 19 '25 09:10

k.m


Unless construction of the class is expensive, do it every test. Guarantee you have a clean slate. You're right, you don't need to do any cleanup at test end either, unless the specific thing you're testing needs it (database connections closing, closing handshakes for web protocols, etc)

like image 27
Bryan Boettcher Avatar answered Oct 19 '25 09:10

Bryan Boettcher