@SpringBootTest

@SpringBootTest — used to load the entire Spring application context for integration testing in Spring Boot.


🧩 Purpose

It allows you to test your app as it would run in production — with all beans, configurations, and environment loaded.


Example:

@SpringBootTest
class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    void testCreateUser() {
        User user = userService.createUser("john", "password");
        assertNotNull(user.getId());
    }
}

✅ This runs with a full Spring context, so UserService and its dependencies (e.g., repositories, security) are all initialized.


🧠 Key Options

  • @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) → starts the server on a random port.
  • @SpringBootTest(classes = MyApp.class) → specify which configuration to load.
  • Slower than unit tests — use for integration or end-to-end tests.

Leave a Reply