Why must jUnit's fixtureSetup be static?

前端 未结 8 1494
悲&欢浪女
悲&欢浪女 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

    there are two types of annotations:

    • @BeforeClass (@AfterClass) called once per test class
    • @Before (and @After) called before each test

    so @BeforeClass must be declared static because it is called once. You should also consider that being static is the only way to ensure proper "state" propagation between tests (JUnit model imposes one test instance per @Test) and, since in Java only static methods can access static data... @BeforeClass and @AfterClass can be applied only to static methods.

    This example test should clarify @BeforeClass vs @Before usage:

    public class OrderTest {
    
        @BeforeClass
        public static void beforeClass() {
            System.out.println("before class");
        }
    
        @AfterClass
        public static void afterClass() {
            System.out.println("after class");
        }
    
        @Before
        public void before() {
            System.out.println("before");
        }
    
        @After
        public void after() {
            System.out.println("after");
        }    
    
        @Test
        public void test1() {
            System.out.println("test 1");
        }
    
        @Test
        public void test2() {
            System.out.println("test 2");
        }
    }
    

    output:

    ------------- Standard Output ---------------
    before class
    before
    test 1
    after
    before
    test 2
    after
    after class
    ------------- ---------------- ---------------
    

提交回复
热议问题