9

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.

MvanGeest
  • 9,406
  • 4
  • 40
  • 41
Manki
  • 3,629
  • 4
  • 24
  • 18

5 Answers5

8

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
  • 12,232
  • 18
  • 72
  • 104
  • 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 Oct 08 '08 at 01:59
  • You can easily verify it by providing a constructor and add a System.out.println to it. – André Oct 08 '08 at 08:08
4

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,614
  • 17
  • 14
  • @BeforeClass is not available in JUnit 3. An equivalent is described here: http://stackoverflow.com/questions/3023091/does-junit-3-have-something-analogous-to-beforeclass – Peter Wippermann Sep 03 '14 at 17:19
3

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 Kock
  • 45,059
  • 7
  • 56
  • 86
2

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
  • 35,223
  • 22
  • 68
  • 90
0

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

orbfish
  • 6,849
  • 13
  • 53
  • 73