JUnit TestCase object instantiation

若如初见. 提交于 2019-12-01 14:56:38

问题


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.


回答1:


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.




回答2:


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




回答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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/181106/junit-testcase-object-instantiation

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