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
there are two types of annotations:
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 ------------- ---------------- ---------------