views:

621

answers:

5

Is a new (or different) instance of TestCase object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?

public class MyTest extends TestCase {
  public void testSomething() { ... }
  public void testSomethingElse() { ... }
}

While running this test, how many instances of MyTest class is created?

If possible, provide a link to a document or source code where I can verify the behaviour.

+6  A: 

Yes, a separate instance is created.

While running that test, 2 instances of MyTest gets created.

If you want a different behavior, one option is to use a similar tool called TestNG(http://testng.org/doc/).

anjanb
Thanks for the quick response. Can you also please provide a link to a document or source code where I can verify this behaviour?
Manki
You can easily verify it by providing a constructor and add a System.out.println to it.
André
+2  A: 

If you are asking this because you are concerned about data being initialized and re-initialized in your constructor, be aware that the prescribed way to initialize your test cases data is via setUp() and tearDown() exclusively.

Chris Noe
+4  A: 

I couldn't find a clear answer in the JUnit docs about your question, but the intent, as anjanb wrote, is that each test is independent of the others, so a new TestCase instance could be created for each test to be run.

If you have expensive test setup ("fixtures") that you want to be shared across all test cases in a test class, you can use the @BeforeClass annotation on a static method to achieve this result: http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html. Note however, that a new instance may still be created for each test, but that won't affect the static data your @BeforeTest method has initialized.

Dov Wasserman
+2  A: 

There's one instance for each test run. Try

public class MyTest extends TestCase {
  public MyTest() { System.out.println("MyTest Constructor");
  public void setUp() { System.out.println("MyTest setUp");
  public void tearDown() { System.out.println("MyTest tearDown");
  public void testSomething() { System.out.println("MyTest testSomething");
  public void testSomethingElse() { System.out.println("MyTest testSomethingElse");
}

The Sourcecode (including that to newer versions - your and my example is Junit 3) is on http://www.junit.org

Olaf
A: 

Yes, definitely. I found that data I stored in instance variables could not be accessed between tests due to this design.

orbfish