JUnit TestCase object instantiation

百般思念 提交于 2019-12-01 16:52:33

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.

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/).

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!