skip to content

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 pageshow

explore

questions

171 · 6 sections

What is the Spring TestContext application-context cache, and why does it exist?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Spring 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.

open as a page

What does @ContextConfiguration do, and how do its `classes` and `locations` attributes differ?

level: juniorimportance: must knowfreq 70%
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.

open as a page

What is @ExtendWith(SpringExtension.class), and what does adding it to a JUnit 5 test class actually do?

level: juniorimportance: must knowfreq 70%
basics
~10 s

SpringExtension 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.

open as a page

What does @ActiveProfiles do in a Spring integration test, and how do you use it?

level: juniorimportance: must knowfreq 70%
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.

open as a page

What attributes make up the TestContext cache key, and what causes two tests to NOT share a context?

level: middleimportance: must knowfreq 55%
basics
~10 s

The 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.

open as a page

How does @SpringBootTest locate the configuration it uses to build the application context when you don't tell it explicitly?

level: juniorimportance: must knowfreq 70%
basics
~10 s

If 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.

open as a page

Why is @SpringBootTest considered expensive/slow, and what exactly does it load?

level: juniorimportance: must knowfreq 70%
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.

open as a page

What does the `properties = {}` attribute of `@SpringBootTest` do, and when would you use it?

level: juniorimportance: must knowfreq 70%
basics
~10 s

It 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.

open as a page

What are the four webEnvironment modes of @SpringBootTest, and what does each one do?

level: juniorimportance: must knowfreq 70%
basics
~10 s

MOCK (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.

open as a page

How do you use ApplicationContextRunner to verify a @ConditionalOnProperty-guarded bean appears only when the property is set? Show the assertions.

level: middleimportance: must knowfreq 38%
basics
~10 s

Chain 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).

open as a page

What is @DataJpaTest and what does it configure?

level: juniorimportance: must knowfreq 78%
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.

open as a page

What is @DataMongoTest and what does it wire up?

level: juniorimportance: must knowfreq 55%
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.

open as a page

What is @JdbcTest and what does it auto-configure for a test?

level: juniorimportance: must knowfreq 55%
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.

open as a page

What is a Spring Boot test slice, and how does a slice like @WebMvcTest differ from @SpringBootTest?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A 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.

open as a page

What is @WebFluxTest and what does it auto-configure for you?

level: juniorimportance: must knowfreq 62%
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.

open as a page

In a MockMvc test, how do you assert that a JSON response body has a field `name` equal to "Ada"?

level: juniorimportance: must knowfreq 80%
basics
~10 s

Use .andExpect(jsonPath("$.name").value("Ada")), statically importing jsonPath from MockMvcResultMatchers. $ is the JSON root and .name navigates to the field.

open as a page

What is MockMvcTester in Spring 6.2, and how do you use it to assert a controller returns 200 with a JSON body?

level: juniorimportance: must knowfreq 70%
basics
~10 s

MockMvcTester (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().

open as a page

What is MockMvc and how do you write a basic controller test with perform and andExpect?

level: juniorimportance: must knowfreq 80%
basics
~10 s

MockMvc 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.

open as a page

What is Spring REST Docs, and how do you enable it and produce a documentation snippet from a MockMvc test?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Spring 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.

open as a page

In a MockMvc test, what does `.andDo(MockMvcResultHandlers.print())` do, and when would you use it?

level: juniorimportance: must knowfreq 62%
basics
~10 s

It 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.

open as a page

What is @MockitoBean and what problem does it solve in a Spring test?

level: juniorimportance: must knowfreq 45%
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(...).

open as a page

What is @MockitoSpyBean and how does it differ from @MockitoBean?

level: juniorimportance: must knowfreq 72%
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.

open as a page

What is @TestConfiguration and how does it differ from a regular @Configuration in a Spring test?

level: juniorimportance: must knowfreq 70%
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.

open as a page

How do you stub a @MockitoBean, and what happens to its stubs and recorded interactions between test methods?

level: middleimportance: must knowfreq 38%
basics
~10 s

Stub 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.

open as a page

What is @TestBean in Spring 6.2 and how do you use it to override a bean in a test?

level: juniorimportance: should knowfreq 22%
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.

open as a page

What is @DynamicPropertySource in Spring Boot testing, and what problem does it solve?

level: juniorimportance: must knowfreq 62%
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.

open as a page

What is Spring Boot's @ServiceConnection annotation and what problem does it solve in integration tests?

level: juniorimportance: must knowfreq 55%
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.

open as a page

What is the @Sql annotation in Spring TestContext, and how do you use it to seed data for an integration test?

level: juniorimportance: must knowfreq 70%
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.

open as a page

What is Testcontainers and why use the @Testcontainers / @Container annotations in a JUnit 5 test?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Testcontainers 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.

open as a page

What is TestEntityManager and why would you use it in a @DataJpaTest instead of your repository?

level: juniorimportance: must knowfreq 45%
basics
~20 s

TestEntityManager 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.

open as a page