Does Junit reinitialize the class with each test method invocation?

前端 未结 5 1936
执笔经年
执笔经年 2020-12-10 11:05

When i run the below code, both test cases come true:

import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MyTest{
    pr         


        
相关标签:
5条回答
  • 2020-12-10 11:44

    Look at the documentation of org.junit.runner.Runner:

    The default runner implementation guarantees that the instances of the test case class will be constructed immediately before running the test and that the runner will retain no reference to the test case instances, generally making them available for garbage collection.

    Unit tests should be independant otherwise it becomes unmaintable. Note that the order of executed methods is not guaranteed (unless you use the annotation @FixMethodOrder).

    0 讨论(0)
  • 2020-12-10 11:47

    If you want to use test class's member variable for all tests , without it being reinitialised to null, then make it static.

    0 讨论(0)
  • 2020-12-10 11:48

    It is because of test isolation.

    No test should depend on another.

    0 讨论(0)
  • 2020-12-10 12:07

    New Instance of MyTest for each test method

    For each test method a new instance of MyTest will be created this is the behavior of Junit.

    So in your case for both methods the variable count will have value 1, and thus the value of count++ will be 2 for both the test methods and hence the test cases pass.

    public class MyTest{
       public MyTest(){
          // called n times
          System.out.println("Constructor called for MyTest");
       }
    
       @Before //called n times
       public void setUp(){
          System.out.println("Before called for MyTest");
       }
    
       //n test methods
    }
    

    If you execute the code above with 2 test methods:

    Output will be:

    Constructor called for MyTest
    Before called for MyTest
    //test execution
    Constructor called for MyTest
    Before called for MyTest
    
    0 讨论(0)
  • 2020-12-10 12:07

    Don't initialize test class state in a constructor unless it is immutable.

    JUnit does not instantiate your test class for every @Test. In fact it only runs methods marked @Before before each one, and will run @BeforeClass methods once before all of the tests in the class.

    However you are not guaranteed that the test runner will actually use just one instance of your test class to run the tests. It is free to use many -- consider running a bunch of tests in parallel, even on different machines.

    While there are JUnit runner settings to control this in general, it's much better to simply follow the JUnit design and initialize test state in a method marked @Before only.

    0 讨论(0)
提交回复
热议问题