What is the @Before annotation in JUnit testing?

The @Before annotation is used when different test cases share the same logic.

The method with the @Before annotation always runs before the execution of each test case.

This annotation is commonly used to develop necessary preconditions for each @Test method.

Syntax

@Before
public void beforeTest() {}

Code

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");
    }
}
@Before Example Code

Explanation

Program Flow

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 @BeforeEach instead of @Before.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved