Search code examples
springtestingjunitannotations

when to use @ExtendWith(SpringExtension.class) and @SpringBootTest it test classes


i currently wonder what is the real difference between this snippet of code

import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
public class TestClass1 {
    
    // some code

}

ant this one..

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestClass2 {
    
    // some code

}

what can we do in the first code that can't do in the 2nd snippet ? and vice-versa : what can we do in the 2nd code that can't do in the 1rst snippet ?

for me, in both cases, we can :

  • use spring context
  • work with junit

so.. what is the difference ?


Solution

  • All that you need to know

    @ExtendWith(SpringExtension.class)

    1. Use to run integration tests and load Spring TestContext
    2. JUnit annotations are also available to use
    3. Not a rich API with respect to configuration

    @SpringBootTest

    1. Use to run integration tests and load Spring TestContext

    2. JUnit annotations are also available to use

    3. Offer a rich API to configure test configuration

    4. Recommended as it supports new features and is simple to use