Integration Testing in Spring Boot
While unit tests check individual components, integration tests check how components work together – database, controllers, services, and external systems. It's like test-driving the complete car instead of just testing the engine separately.
Spring Boot provides excellent support for integration testing with
@SpringBootTest.Basic Integration Test:
@SpringBootTest
@AutoConfigureMockMvc
public class UserIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private UserRepository userRepository;
@BeforeEach
public void setup() {
userRepository.deleteAll();
}
@Test
public void testCreateAndGetUser() throws Exception {
// Create user via API
String userJson = "{""name"":""John",""email"":""john@example.com""}";
MvcResult createResult = mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isOk())
.andReturn();
// Extract created user ID
String response = createResult.getResponse().getContentAsString();
Long userId = JsonPath.parse(response).read("$.id", Long.class);
// Get user via API
mockMvc.perform(get("/api/users/" + userId))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is("John")))
.andExpect(jsonPath("$.email", is("john@example.com")));
// Verify database directly
User savedUser = userRepository.findById(userId).orElse(null);
assertNotNull(savedUser);
assertEquals("John", savedUser.getName());
}
}
Testing with Test Database:
Use H2 in-memory database for testing:
# application-test.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
@SpringBootTest
@ActiveProfiles("test")
public class DatabaseIntegrationTest { ... }
Testing Data Layer Only:
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
public void testFindByEmail() {
// Given
User user = new User("John", "john@example.com");
entityManager.persist(user);
entityManager.flush();
// When
User found = userRepository.findByEmail("john@example.com");
// Then
assertThat(found.getName()).isEqualTo("John");
}
}
Testing REST Clients with @RestClientTest:
@RestClientTest(UserClient.class)
public class UserClientTest {
@Autowired
private UserClient userClient;
@Autowired
private MockRestServiceServer server;
@Test
public void testGetUser() {
server.expect(requestTo("/api/users/1"))
.andRespond(withSuccess("{""id"":1,""name"":""John""}", MediaType.APPLICATION_JSON));
User user = userClient.getUser(1L);
assertEquals("John", user.getName());
}
}
Two Minute Drill
- @SpringBootTest loads full application context for integration testing.
- @AutoConfigureMockMvc enables MockMvc for controller testing.
- Use @DataJpaTest for repository layer tests.
- Use @RestClientTest for REST client tests.
- @ActiveProfiles selects specific configuration for tests.
- Use in-memory database (H2) for faster tests.
Need more clarification?
Drop us an email at career@quipoinfotech.com
