The @Before annotation is used when different test cases share the same logic.
The method with the
@Beforeannotation always runs before the execution of each test case.
This annotation is commonly used to develop necessary preconditions for each @Test method.
@Before
public void beforeTest() {}
Let’s run the code for the @Before annotation.
import org.junit.*;
public class demoTest {
//indicates that this method will run before the each @Test method
@Before
public void beforetest() {
System.out.println("@Before method is running");
}
//First testcase
@Test
public void testcase1() {
System.out.println("Testcase 1 is running");
}
//Second testcase
@Test
public void testcase2() {
System.out.println("Testcase 2 is running");
}
}As you can see, the method with the @Before annotation is run twice. OK (2 tests) indicates that both test cases are passing.
Keep in mind that JUnit 5 supports
@BeforeEachinstead of@Before.
Free Resources