Java - Spring - Test - Context - @SpringBootTest

Java - Spring - Test - Context - @SpringBootTest

1 - @SpringBootTest Overview

  • used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features (e.g. logging & properties)
  • creates the ApplicationContext to be used in tests

2 - Code Example

@SpringBootTest automatically picks up all classes annotated with @SpringBootConfiguration/@SpringBootApplication

@SpringBootTest
class MainApplicationTest {
  @Test
  void testCheckout() {
  }
}

@SpringBootTest(classes = MainApplication.class) will only pick up JUST the specified MainApplication.class

@SpringBootTest(classes = MainApplication.class)
class MainApplicationTest {
  @Test
  void testCheckout() {
  }
}

3 - Customize @SpringBootTest

adding auto-configure

@AutoConfigureMockMvc
@SpringBootTest
public class TestApplicationContext_AddAutoConfigures_JUnit5Test {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void test() {
        Assert.assertNotNull(mockMvc);
    }
}

adding properties

@SpringBootTest(properties = "turkey=legs")
public class TestApplicationContext_AddProperties_JUnit5Test {
    @Value("${turkey}")
    String foo;

    @Test
    public void test() {
        Assert.assertEquals("legs", foo);
    }
}