Why does a TestCase get instantiated as many times as it contains test methods?

Try this:

public class MyTest extends TestCase {

  public MyTest(String name) {
    System.out.println(“Created a MyTest”);

  public void testA() {}

  public void testB() {}

and you will see “Created a MyTest” displayed twice.

My initial reaction when I see code that puzzles me is to give the author the
benefit of the doubt, so my first thought was “Maybe they do this to make sure that test methods are independent from each other, that is, a test cannot fail because of a side effect created by another test method”.

Then I realized that this justification was stupid for two reasons:

  • If I want two test methods to be truly independent, I will just put them in two different classes.
  • The setUp() method is called before each test method, thus guaranteeing that the state of the object is restored before each invocation.

The more I thought about it, the more I realized that being able to share some state between test methods, such as a JDBC connection or a parsed XML file, was actually quite useful. The problem is that JUnit
makes this simply impossible:  you have to put this code in setUp() and
therefore, rerun it before every test method.

At this point, and after finding all these deficiencies in JUnit’s design and implementation, I am beginning to think we are once more stuck with a de facto standard that is utterly broken.

Unless someone can explain to me this behavior?