Testing
Spring's testing support: the TestContext framework and its context cache, @SpringBootTest, the test slices, MockMvc and WebTestClient, bean mocking, and Testcontainers. Interviewers ask because slow, over-broad tests are one of the most common problems in a Spring codebase.
part ofSpring Frameworkoverview, primer and where to startread it →on this pageshowhide
explore
- Spring TestContext Framework25 questions
- @ContextConfiguration & Context Loading5 questions
- Context Caching & @DirtiesContext5 questions
- TestExecutionListeners5 questions
- @ActiveProfiles & @TestPropertySource5 questions
- SpringExtension & JUnit Jupiter5 questions
- @SpringBootTest & Full Context26 questions
- webEnvironment Modes5 questions
- Configuration Detection5 questions
- Test Properties & Arguments5 questions
- Full-Context Cost & When to Slice5 questions
- ApplicationContextRunner6 questions
- Test Slices29 questions
- How Slices Work5 questions
- @WebMvcTest5 questions
- @DataJpaTest5 questions
- @JdbcTest & @JsonTest5 questions
- @WebFluxTest & @RestClientTest5 questions
- @DataMongoTest & Other Data Slices4 questions
- Endpoint Testing & Assertions40 questions
- MockMvc API5 questions
- MockMvcTester (AssertJ)5 questions
- WebTestClient5 questions
- JSONPath & Content Assertions5 questions
- Result Handlers & Debugging5 questions
- Spring REST Docs5 questions
- Spring Security Test Support5 questions
- TestRestTemplate5 questions
- Mocking Collaborators & Test Fixtures20 questions
- @MockitoBean5 questions
- @MockitoSpyBean5 questions
- @TestBean5 questions
- @TestConfiguration & Fixtures5 questions
- Persistence & Integration Testing31 questions
- Transactional Tests & Rollback6 questions
- @Sql Script Execution5 questions
- TestEntityManager5 questions
- @Testcontainers & @Container5 questions
- @ServiceConnection5 questions
- @DynamicPropertySource5 questions
questions
171 · 6 sectionsWhat is the Spring TestContext application-context cache, and why does it exist?
basics
~10 sSpring starts the application context once and reuses (caches) it across test classes that ask for the same configuration, instead of rebuilding it per test. This makes the whole test suite much faster.
What does @ContextConfiguration do, and how do its `classes` and `locations` attributes differ?
basics
~10 s@ContextConfiguration tells the Spring TestContext Framework how to build the ApplicationContext for a test. classes points to @Configuration/component classes; locations (or value) points to XML or Groovy resource files.
What is @ExtendWith(SpringExtension.class), and what does adding it to a JUnit 5 test class actually do?
basics
~10 sSpringExtension is the JUnit 5 hook that plugs Spring's TestContext into your test. Adding @ExtendWith(SpringExtension.class) lets Spring build an ApplicationContext and inject beans (e.g. via @Autowired) into the test.
What does @ActiveProfiles do in a Spring integration test, and how do you use it?
basics
~10 s@ActiveProfiles activates one or more Spring bean-definition profiles for a test's ApplicationContext. You put it on the test class, e.g. @ActiveProfiles("test"), so beans and property files tied to that profile are loaded.
What attributes make up the TestContext cache key, and what causes two tests to NOT share a context?
basics
~10 sThe key is the merged test configuration: the config classes/locations, active profiles, property sources and inlined properties, context initializers, the context loader, and context customizers (like added mocks). Any difference means a separate context.
How does @SpringBootTest locate the configuration it uses to build the application context when you don't tell it explicitly?
basics
~10 sIf you don't specify classes, @SpringBootTest searches the test's package and then walks up parent packages until it finds a class annotated with @SpringBootConfiguration (usually your @SpringBootApplication main class) and uses that.
Why is @SpringBootTest considered expensive/slow, and what exactly does it load?
basics
~10 s@SpringBootTest starts the full Spring application context — every bean, all auto-configurations, and (optionally) an embedded web server. Building that whole context takes seconds, so tests run slowly.
What does the `properties = {}` attribute of `@SpringBootTest` do, and when would you use it?
basics
~10 sIt sets configuration properties just for that test, in key=value form. Those values override the same keys from application.properties, so you can test the app under specific config without editing real files.
What are the four webEnvironment modes of @SpringBootTest, and what does each one do?
basics
~10 sMOCK (default) loads a mock servlet environment, no real port. RANDOM_PORT and DEFINED_PORT start a real embedded server on a random or fixed port. NONE loads the context with no web environment at all.
How do you use ApplicationContextRunner to verify a @ConditionalOnProperty-guarded bean appears only when the property is set? Show the assertions.
basics
~10 sChain withPropertyValues("feature.enabled=true") before run(), then inside the lambda assert assertThat(context).hasSingleBean(Foo.class). For the off case, omit or set the property false and assert doesNotHaveBean(Foo.class).
What is @DataJpaTest and what does it configure?
basics
~20 s@DataJpaTest is a Spring Boot test slice for the persistence layer. It loads only JPA-related beans — your @Repository beans, EntityManager, and DataSource — plus a TestEntityManager, and by default runs against an in-memory embedded database.
What is @DataMongoTest and what does it wire up?
basics
~20 s@DataMongoTest is a Spring Boot test slice that loads only the MongoDB-related parts of the context — your Spring Data Mongo repositories and MongoTemplate — instead of the whole application, so repository tests start fast.
What is @JdbcTest and what does it auto-configure for a test?
basics
~10 s@JdbcTest is a Spring Boot test slice for plain JDBC/JdbcTemplate code. It loads only JDBC beans plus an in-memory database, wraps each test in a rolled-back transaction, and skips the rest of the app.
What is a Spring Boot test slice, and how does a slice like @WebMvcTest differ from @SpringBootTest?
basics
~20 sA test slice loads only the part of the application relevant to one layer (e.g. web MVC) instead of the whole app. @SpringBootTest starts the full context; @WebMvcTest loads only web components, so tests are faster and focused.
What is @WebFluxTest and what does it auto-configure for you?
basics
~20 s@WebFluxTest is a sliced Spring Boot test that loads only the reactive web layer — your @RestController/@Controller and WebFlux infrastructure — not the whole app. It auto-configures a WebTestClient so you can call your endpoints in tests.
In a MockMvc test, how do you assert that a JSON response body has a field `name` equal to "Ada"?
basics
~10 sUse .andExpect(jsonPath("$.name").value("Ada")), statically importing jsonPath from MockMvcResultMatchers. $ is the JSON root and .name navigates to the field.
What is MockMvcTester in Spring 6.2, and how do you use it to assert a controller returns 200 with a JSON body?
basics
~10 sMockMvcTester (Spring 6.2) is a fluent, AssertJ-based wrapper around MockMvc. You perform a request like mvc.get().uri("/x") and pass it to AssertJ's assertThat(...), then chain checks such as .hasStatusOk() and .bodyJson().
What is MockMvc and how do you write a basic controller test with perform and andExpect?
basics
~10 sMockMvc lets you test Spring MVC controllers without starting a real HTTP server. You call mockMvc.perform(get("/url")) to send a fake request, then chain andExpect(status().isOk()) to assert on the response.
What is Spring REST Docs, and how do you enable it and produce a documentation snippet from a MockMvc test?
basics
~10 sSpring REST Docs generates API documentation from passing tests. You add @AutoConfigureRestDocs to a @WebMvcTest, then call MockMvc's perform(...).andDo(document("identifier")) to capture the request and response as reusable snippets.
In a MockMvc test, what does `.andDo(MockMvcResultHandlers.print())` do, and when would you use it?
basics
~10 sIt prints the full request and response (URL, headers, status, body, handler) to System.out after the request runs. You add it to debug a failing test and see what the endpoint actually returned.
What is @MockitoBean and what problem does it solve in a Spring test?
basics
~10 s@MockitoBean (Spring 6.2) is a test-field annotation that replaces a real bean in the loaded Spring ApplicationContext with a Mockito mock, so collaborators receive the fake and you control its behaviour with when(...).thenReturn(...).
What is @MockitoSpyBean and how does it differ from @MockitoBean?
basics
~20 s@MockitoSpyBean wraps a real Spring bean in a Mockito spy: real methods run by default, but you can stub or verify them. @MockitoBean replaces the bean with a full mock whose methods do nothing until stubbed.
What is @TestConfiguration and how does it differ from a regular @Configuration in a Spring test?
basics
~20 s@TestConfiguration is a special @Configuration used only in tests. It adds or overrides beans on top of your app's real configuration, instead of replacing it. A plain @Configuration found via scanning would replace the primary config.
How do you stub a @MockitoBean, and what happens to its stubs and recorded interactions between test methods?
basics
~10 sStub with Mockito: when(mock.method(args)).thenReturn(value) (or given(...).willReturn(...)). By default Spring resets the mock after each test method, so stubs and verify() history do not leak between tests.
What is @TestBean in Spring 6.2 and how do you use it to override a bean in a test?
basics
~10 s@TestBean (Spring 6.2) replaces a bean in the test's application context with an instance you build in a static factory method inside the test class. By convention the method is named <fieldName>TestOverride.
What is @DynamicPropertySource in Spring Boot testing, and what problem does it solve?
basics
~10 s@DynamicPropertySource marks a static test method that registers property values computed at runtime — like a Testcontainers database's random mapped port or JDBC URL — into Spring's Environment before the application context starts.
What is Spring Boot's @ServiceConnection annotation and what problem does it solve in integration tests?
basics
~20 s@ServiceConnection is a Spring Boot annotation you put on a Testcontainers container. Boot reads the container's real URL, port, username and password and wires your app's beans (like the DataSource) to it automatically, so you don't set those properties by hand.
What is the @Sql annotation in Spring TestContext, and how do you use it to seed data for an integration test?
basics
~20 s@Sql runs SQL scripts (or inline statements) against the test's DataSource before a test method. You point it at a .sql file on the classpath, e.g. @Sql("/data.sql"), to insert seed rows before the test runs.
What is Testcontainers and why use the @Testcontainers / @Container annotations in a JUnit 5 test?
basics
~20 sTestcontainers starts a real service (like PostgreSQL) in a throwaway Docker container for tests. @Testcontainers on the class turns on lifecycle management, and @Container marks a container field so it is started before tests and stopped after.
What is TestEntityManager and why would you use it in a @DataJpaTest instead of your repository?
basics
~20 sTestEntityManager is a Spring Boot test helper auto-configured by @DataJpaTest. It wraps JPA's EntityManager with test-friendly methods (persist, persistAndFlush, persistFlushFind, find, flush, clear) to set up database rows for a test without going through the repository you're testing.