Spring Boot Testing Spring Applications Questions and Answers — Questions and Answers
Question 1: A developer needs to write a test for a Spring MVC `@RestController` that focuses exclusively on the web layer. The test should verify request mappings, JSON serialization/deserialization, and exception handling without loading the service or repository layers. Which annotation is most suitable for this purpose?
- `@SpringBootTest`
- `@WebMvcTest(MyController.class)` (Correct answer)
- `@DataJpaTest`
- `@ExtendWith(MockitoExtension.class)`
Correct answer: `@WebMvcTest(MyController.class)`
`@WebMvcTest` is a test slice annotation that sets up an application context containing only the beans necessary for testing the web layer, such as controllers, filters, and MVC infrastructure. [7, 11, 12] It does not load `@Service` or `@Repository` beans, making it lightweight and fast for focused controller testing. [7, 18] `@SpringBootTest` loads the entire application context, `@DataJpaTest` focuses on the persistence layer, and `@ExtendWith(MockitoExtension.class)` is a general JUnit 5 extension for Mockito, not specific to Spring's web layer testing.
Question 2: In a Spring Boot integration test annotated with `@SpringBootTest`, what is the primary function of the `@MockBean` annotation?
- To create a mock object that is not part of the Spring `ApplicationContext`.
- To inject a real bean from the `ApplicationContext` into the test class.
- To add a new bean or replace an existing bean in the `ApplicationContext` with a Mockito mock. (Correct answer)
- To configure a specific test profile for the `ApplicationContext`.
Correct answer: To add a new bean or replace an existing bean in the `ApplicationContext` with a Mockito mock.
The `@MockBean` annotation is used in Spring Boot tests to add a Mockito mock to the `ApplicationContext`. [1] If a bean of the same type already exists, it will be replaced by the mock. This allows you to simulate the behavior of a dependency (like a service or repository) within a full or sliced application context test, isolating the component under test from its actual dependencies. [8, 16] The mock is automatically reset after each test method. [1]
Question 3: When writing a test class annotated with `@DataJpaTest`, which of the following behaviors is NOT part of its default configuration?
- Configuring an in-memory embedded database (like H2).
- Scanning for `@Entity` classes and Spring Data repositories.
- Executing each test method within a transaction that is rolled back by default.
- Loading the full application context, including web controllers and services. (Correct answer)
Correct answer: Loading the full application context, including web controllers and services.
`@DataJpaTest` is a test slice annotation focused on testing the persistence layer. By default, it disables full auto-configuration and only loads JPA-related components like repositories and entities. [5, 9, 13] It also configures an in-memory database and makes tests transactional with automatic rollback. [4, 15] It specifically does NOT load other beans like `@Controller` or `@Service` to keep the tests fast and focused on data access logic. [5]
Question 4: A developer needs to write a full integration test for a REST API. The test must start the application on an actual (but random) port and make real HTTP requests to the endpoints to verify the complete request-response cycle. Which annotation and helper class combination is best suited for this scenario?
- `@WebMvcTest` and `MockMvc`
- `@SpringBootTest(webEnvironment = WebEnvironment.MOCK)` and `MockMvc`
- `@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)` and `TestRestTemplate` (Correct answer)
- `@DataJpaTest` and `TestEntityManager`
Correct answer: `@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)` and `TestRestTemplate`
To perform a full-stack integration test with a running server, `@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)` is used. This starts the embedded server on a random port. [6, 17, 20] The `TestRestTemplate` is a utility provided by Spring Boot specifically for making live HTTP calls to the running application in such integration tests. [2, 20] In contrast, `MockMvc` operates on a mocked servlet environment without a real server. [2, 14]
Question 5: An integration test requires a database connection whose JDBC URL is determined at runtime by a Testcontainers-managed Docker container. Which annotation should be used on a static method within the test class to add this dynamically generated URL to the Spring `Environment` before the context is refreshed?
- `@TestPropertySource(properties = "spring.datasource.url=...")`
- `@DynamicPropertySource` (Correct answer)
- `@ContextConfiguration`
- `@ActiveProfiles("test-container")`
Correct answer: `@DynamicPropertySource`
`@DynamicPropertySource` is specifically designed to add properties with values that are not known until runtime, such as the dynamic port or URL of a service started by Testcontainers. [10, 21, 22] It must be used on a static method that accepts a `DynamicPropertyRegistry`. `@TestPropertySource` is for static properties, `@ContextConfiguration` is for customizing the context, and `@ActiveProfiles` activates profiles but doesn't set dynamic properties.
Question 6: A developer wants to run a specific test class using a 'test' profile, which configures an in-memory database defined in an `application-test.properties` file. How can they ensure this profile is activated for just that one test class?
- By adding `spring.profiles.active=test` to the main `application.properties` file.
- By annotating the test class with `@Profile("test")`.
- By passing a command-line argument `-Dspring.profiles.active=test` when running the test.
- By annotating the test class with `@ActiveProfiles("test")`. (Correct answer)
Correct answer: By annotating the test class with `@ActiveProfiles("test")`.
The `@ActiveProfiles` annotation is used on a test class to declare which bean definition profiles should be active when loading the `ApplicationContext` for that specific integration test. [32, 33] This allows developers to selectively activate certain configurations for testing purposes without affecting other tests or the main application configuration.
A developer needs to write a test for a Spring MVC `@RestController` that focuses exclusively on the web layer.
The test should verify request mappings, JSON serialization/deserialization, and exception handling without loading the service or repository layers.
Which annotation is most suitable for this purpose?