Loading

Quipoin Menu

Learn • Practice • Grow

spring / Integration Testing in Spring Boot
interview

Q1. What is integration testing in Spring?
Integration testing involves testing multiple layers together, often with a real or embedded database. Spring Boot provides @SpringBootTest to load the full application context, allowing you to test the complete stack.

Q2. What is @SpringBootTest?
@SpringBootTest annotation tells Spring Boot to look for the main configuration class and create an application context for tests. It can be used to test the entire application. You can specify webEnvironment to run on a random port, etc.

Q3. How do you test a REST API with Spring Boot?
Use @SpringBootTest with webEnvironment = RANDOM_PORT and @AutoConfigureMockMvc or TestRestTemplate. TestRestTemplate can make real HTTP calls to the embedded server. Example:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class ApiTest { @LocalServerPort int port; @Autowired TestRestTemplate restTemplate; @Test void testGet() { ResponseEntity response = restTemplate.getForEntity("/users/1", User.class); assertEquals(200, response.getStatusCodeValue()); } }

Q4. How do you test database interactions?
Use @DataJpaTest to test JPA repositories. It loads only JPA-related beans and uses an in-memory database by default. You can then inject repository and test CRUD operations.

Q5. How do you mock external services in integration tests?
Use @MockBean to replace external service beans with mocks. For HTTP clients, you might use WireMock to stub external APIs. This allows you to test your application's integration points without calling real services.