Does Junit reinitialize the class with each test method invocation?

前端 未结 5 1950
执笔经年
执笔经年 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 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.

提交回复
热议问题