Home > AI > Backend > SpringBoot > Junit >

@Before

  • @Before @After annotations
    • Run before and after every test method in the class
  • @BeforeClass @AfterClass annotations
    • Static methods which are executed once before and after a test class

@Before works with Junit4.class, not with @SpringBootTest

@BeforeEach works with @SpringBootTest

Junit4SpringBootTest
before each test@Before@BeforeEach
after each test@After@AfterEach
before the class@BeforeClass

Example (Junit)

@Slf4j
@RunWith(JUnit4.class)
public class TestJunit {


    private List<String> list;

    @Before
    public void init() {
        log.info("[Shark] startup");
        list = new ArrayList<>(Arrays.asList("test1", "test2"));
    }

    @After
    public void teardown() {
        log.info("[Shark] teardown");
        list.clear();
    }

    @Test
    public void middle() {
        log.info("[Shark] middle");
    }
}

It works

Example (SpringBoot)

@Slf4j
@SpringBootTest
public class TestSpringBoot {

    private List<String> list;

    @Before
    public void init() {
        log.info("[Shark] startup-springboot");
        list = new ArrayList<>(Arrays.asList("test1", "test2"));
    }

    @After
    public void teardown() {
        log.info("[Shark] teardown-springboot");
        list.clear();
    }

    @Test
    public void middle() {
        log.info("[Shark] middle-springboot");
    }
}

It doesn’t work

Leave a Reply