Spring Boot Testing Spring Applications 2 — Questions and Answers
Question 1: Which annotation replaces the full application context with only web-layer beans during testing?
- @SpringBootTest
- @WebMvcTest (Correct answer)
- @DataJpaTest
- @ContextConfiguration
Correct answer: @WebMvcTest
@WebMvcTest loads only the MVC layer (controllers, filters, converters) without starting a full application context.
Question 2: What does the @DataJpaTest annotation do by default regarding the database?
- Connects to the configured production datasource
- Uses an in-memory embedded database and rolls back each test (Correct answer)
- Disables all transaction management
- Starts a full Spring context including all beans
Correct answer: Uses an in-memory embedded database and rolls back each test
@DataJpaTest auto-configures an embedded in-memory database and wraps each test in a transaction that rolls back after the test.
Question 3: How can you inject a mock bean into the Spring application context using Mockito?
- @MockBean (Correct answer)
- @InjectMocks
- @Mock
- @Spy
Correct answer: @MockBean
@MockBean creates a Mockito mock and registers it as a Spring bean, replacing any existing bean of that type in the context.
Question 4: Which class is used to perform HTTP requests in MockMvc-based tests?
- TestRestTemplate
- MockMvcRequestBuilders (Correct answer)
- WebTestClient
- RestAssured
Correct answer: MockMvcRequestBuilders
MockMvcRequestBuilders provides static factory methods like get(), post(), put(), and delete() for constructing MockMvc requests.
Question 5: In a @SpringBootTest test, what webEnvironment setting starts an actual HTTP server on a random port?
- MOCK
- NONE
- RANDOM_PORT (Correct answer)
- DEFINED_PORT
Correct answer: RANDOM_PORT
RANDOM_PORT starts an embedded server on a random available port, and you can inject the port with @LocalServerPort.
Question 6: What is the purpose of the @Sql annotation in Spring test support?
- Generates SQL schema from JPA entities
- Executes SQL scripts before or after a test method (Correct answer)
- Validates SQL query syntax at startup
- Profiles slow SQL queries during tests
Correct answer: Executes SQL scripts before or after a test method
@Sql allows you to specify SQL scripts to run against the database before or after a test method or class.
Question 7: Which assertion method in MockMvc verifies the HTTP response status code?
- andExpect(status().isOk()) (Correct answer)
- andAssert(status(200))
- thenReturn(HttpStatus.OK)
- verify(status().is(200))
Correct answer: andExpect(status().isOk())
andExpect(status().isOk()) chains a ResultMatcher that asserts the response status is 200 OK.
Which annotation replaces the full application context with only web-layer beans during testing?