Spring Boot @SpringBootTest Example

1. Introduction

Integration tests in Spring Boot allow developers to verify the interactions between different layers of the application stack, such as the database, repositories, services, and controllers. Using @SpringBootTest, we can create tests that load the entire application context and perform operations just like in a running application.

Key Points:

1. @SpringBootTest enables integration testing by starting the full application context.

2. Tests involve real database interactions, and they can use @DataJpaTest for repository tests.

3. Service layer tests use the actual service beans, and controller tests can perform simulated HTTP requests.

2. Implementation Steps

1. Define the domain model and repository interface for database interaction.

2. Implement the service layer that uses the repository.

3. Create the REST controller that delegates business actions to the service layer.

4. Configure application properties for database connection.

5. Write an integration test with @SpringBootTest to test the entire stack.

3. Implementation Example

// Domain model
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    // getters and setters
}

// Repository layer
public interface UserRepository extends JpaRepository<User, Long> {
    // Query methods
}

// Service layer
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User createUser(String name) {
        User newUser = new User();
        newUser.setName(name);
        return userRepository.save(newUser);
    }
    // Other business methods
}

// Controller layer
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public ResponseEntity<User> createUser(@RequestParam String name) {
        User user = userService.createUser(name);
        return new ResponseEntity<>(user, HttpStatus.CREATED);
    }
    // Other endpoints
}

// Integration Test
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testCreateUser() throws Exception {
        mockMvc.perform(post("/users").param("name", "John Doe"))
               .andExpect(status().isCreated())
               .andExpect(jsonPath("$.name").value("John Doe"));
    }
    // Other test methods
}

// Application properties (src/main/resources/application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/myapp_test
spring.datasource.username=testuser
spring.datasource.password=testpass
spring.jpa.hibernate.ddl-auto=create-drop

// Main class
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

// Run the test using a command line or an IDE.

Output:

// When running the integration test, the output will display whether the test passed or failed, along with any error messages.

Explanation:

1. User is the domain model annotated with @Entity, mapping to a table in the MySQL database.

2. UserRepository extends JpaRepository, providing CRUD operations for User entities.

3. UserService is the service layer bean that contains business logic and interacts with UserRepository.

4. UserController is a REST controller exposing the endpoint to create new users.

5. UserControllerIntegrationTest is the test class annotated with @SpringBootTest, loading the full application context for integration testing.

6. @AutoConfigureMockMvc is used in the test to inject MockMvc for simulating HTTP requests and verifying responses.

7. The testCreateUser method simulates posting to the "/users" endpoint and verifies the outcome using MockMvc.

8. The application properties define the MySQL database connection and set Hibernate to create and drop the database schema automatically.

9. MyApp is the main application class with the main method to start the application.

10. When the integration test is executed, it should confirm that a User can be created through the REST endpoint and persisted in the MySQL database, verifying the integration of the controller, service, and repository layers.


Comments