Search code examples
javajunitinstantiationtestcase

JUnit TestCase object instantiation


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.


Solution

  • 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.