Why must jUnit's fixtureSetup be static?

前端 未结 8 1469
悲&欢浪女
悲&欢浪女 2020-12-04 07:50

I marked a method with jUnit\'s @BeforeClass annotation, and got this exception saying it must be static. What\'s the rationale? This forces all my init to be on static fiel

8条回答
  •  有刺的猬
    2020-12-04 08:45

    It seems that JUnit creates a new instance of the test class for each test method. Try this code out

    public class TestJunit
    {
    
        int count = 0;
    
        @Test
        public void testInc1(){
            System.out.println(count++);
        }
    
        @Test
        public void testInc2(){
            System.out.println(count++);
        }
    
        @Test
        public void testInc3(){
            System.out.println(count++);
        }
    }
    

    The output is 0 0 0

    This means that if the @BeforeClass method is not static then it will have to be executed before each test method and there would be no way to differentiate between the semantics of @Before and @BeforeClass

提交回复
热议问题