0
0
JUnittesting~5 mins

Spring Boot @SpringBootTest in JUnit

Choose your learning style9 modes available
Introduction

The @SpringBootTest annotation helps you test your whole Spring Boot app easily. It starts the app context so you can check if everything works together.

When you want to test if your Spring Boot app loads without errors.
When you need to test multiple parts of your app working together.
When you want to test your app with real Spring beans and configurations.
When you want to check if your app's services and repositories interact correctly.
When you want to run integration tests that need the full app context.
Syntax
JUnit
@SpringBootTest
public class YourTestClass {
    // test methods here
}

This annotation tells Spring Boot to start the full application context for testing.

You usually use it on a test class, not on individual methods.

Examples
Basic test to check if the Spring Boot app context loads without errors.
JUnit
@SpringBootTest
public class MyAppTests {

    @Test
    void contextLoads() {
        // test if context starts
    }
}
Starts the app with a random port to test web endpoints using TestRestTemplate.
JUnit
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebLayerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void testHomePage() {
        String body = restTemplate.getForObject("/", String.class);
        assertTrue(body.contains("Welcome"));
    }
}
Sample Program

This simple test checks if the Spring Boot application context loads without any errors. If it loads, the test passes.

JUnit
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@SpringBootTest
public class SimpleSpringBootTest {

    @Test
    void contextLoads() {
        // This test will pass if the app context loads successfully
        assertNotNull(this);
    }
}
OutputSuccess
Important Notes

Use @SpringBootTest for integration tests, not for small unit tests.

Starting the full app context can make tests slower, so use it only when needed.

You can customize the environment with parameters like webEnvironment to test web layers.

Summary

@SpringBootTest starts the full Spring Boot app context for testing.

It is useful for integration tests that check how parts of your app work together.

Use it carefully because it can slow down your tests if overused.