skip to content

Test Slices

Boot's test slices load just one layer — web, JPA, JSON, a client — instead of the whole application. Interviewers ask which slice fits a given test, because that choice drives both speed and what the test really proves.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

explore

questions

29

What is @DataJpaTest and what does it configure?

level: juniorimportance: must knowfreq 78%

answer

  1. Persistence-layer test slice
  2. Repositories + EntityManager + TestEntityManager
  3. Embedded DB by default
  4. No services/controllers
  5. Transactional, rolls back

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.

solid answer

~40 s

@DataJpaTest is a Spring Boot 'test slice' annotation that boots a minimal context focused on JPA persistence instead of the whole application. It auto-configures Hibernate/JPA, scans @Entity classes, registers your Spring Data JPA repositories, and provides a TestEntityManager helper. By default it swaps your real DataSource for an in-memory embedded database (H2/HSQLDB/Derby) via @AutoConfigureTestDatabase, and each test method runs inside a transaction that rolls back at the end so tests stay isolated. It deliberately does NOT load @Service, @Controller, @Component, or web/security beans, which makes it far faster to start than @SpringBootTest. Use it to test queries, repository methods, mappings, and constraints in isolation.

code

java · 18 lines
java
@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository; // Spring Data repo is available

    @Autowired
    private TestEntityManager em;          // provided by @DataJpaTest

    @Test
    void findsByEmail() {
        em.persistAndFlush(new User("[email protected]"));

        Optional<User> found = userRepository.findByEmail("[email protected]");

        assertThat(found).isPresent();
    }
}

go deeper

for a junior

Know it's a persistence slice: loads repositories + JPA, uses an embedded DB, doesn't load the whole app.

for a middle

Articulate exactly what's included vs excluded and why it's faster than @SpringBootTest.

for a senior

Explain the auto-configuration imports (@AutoConfigureTestDatabase, TestEntityManager) and the trade-off of testing on H2 vs the real DB.

for a principal

Frame slices as a context-cost/fidelity trade-off and when a team should standardize on Testcontainers instead.

## What it is `@DataJpaTest` is one of Spring Boot's **test slice** annotations (package `org.springframework.boot.test.autoconfigure.orm.jpa`). A test slice starts a **partial** application context containing only the beans relevant to one layer — here, the JPA/persistence layer — rather than the entire application the way `@SpringBootTest` does. This makes the context small and fast to start. ## What gets loaded When you put `@DataJpaTest` on a test class, Spring Boot auto-configures: - **JPA + Hibernate**: an `EntityManagerFactory`/`EntityManager`, the Hibernate `SessionFactory`, and entity scanning (`@Entity` classes are picked up). - **Spring Data JPA repositories**: interfaces extending `JpaRepository`/`CrudRepository` are registered as beans so you can `@Autowired` them. - **A `DataSource`** — by default an **embedded in-memory database** (see below). - **`TestEntityManager`**: a test-friendly wrapper around `EntityManager` (with helpers like `persistAndFlush`, `find`). - **Transaction management** (`PlatformTransactionManager`). ## What is NOT loaded This is the key point of a slice: `@Service`, `@Component`, `@Controller`/`@RestController`, Spring MVC, Spring Security filters, and other `@Configuration` beans are **excluded**. If your repository test needs one of those, you must provide it yourself (e.g. `@Import`, `@MockBean`, or a nested test config). ## Default embedded database By default `@DataJpaTest` includes `@AutoConfigureTestDatabase`, which **replaces** any configured `DataSource` with an embedded one (H2, HSQLDB, or Derby if on the classpath). This means your tests do NOT hit your production database. You can turn this off to test against the real configured DB (see the follow-up questions). ## Transactional by default Each test method runs inside a transaction that is **rolled back** at the end, so tests don't leave data behind and don't interfere with each other. (The exact rollback mechanics and `TestEntityManager` usage are covered by the sibling data-integration topic.) ## When to use - Testing custom `@Query` methods, derived query methods, projections. - Verifying entity mappings, column constraints, cascade/orphan behavior. - Checking that unique/nullability constraints fire. ## When NOT to use - You need the full stack (controllers, services) — use `@SpringBootTest`. - You want to test against a production-like DB with vendor-specific SQL — combine with Testcontainers and disable the embedded replacement. ## Gotchas - Forgetting an embedded driver on the classpath → context fails to start. - Assuming your `@Service` is available — it isn't in the slice. - Vendor-specific SQL passing on H2 but failing on Postgres in production.

  • Is your @Service bean available inside a @DataJpaTest?
    No. Slices exclude @Service/@Component/@Controller. You'd need @Import, a nested @TestConfiguration, or @MockBean to bring one in — or use @SpringBootTest for the full context.
  • Which database does @DataJpaTest use by default and why?
    An in-memory embedded database (H2/HSQLDB/Derby) because @DataJpaTest includes @AutoConfigureTestDatabase, which replaces the real DataSource so tests are fast and don't touch production data.

saying these in an interview costs you the question

  • Thinking @DataJpaTest loads the whole application context
  • Believing @Service beans are injectable inside the slice
  • Assuming it runs against the production database by default

context

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

What is @WebMvcTest and what does it load (and not load) into the Spring context?

level: juniorimportance: must knowfreq 82%

basics

~10 s

@WebMvcTest is a Spring Boot test annotation that starts only the web/MVC layer — your controllers plus MockMvc — without loading services, repositories, or the full application. It makes controller tests fast and focused.

open as a page

By default @DataJpaTest replaces your DataSource with an embedded DB. How do you test against the real (production-like) database instead?

level: middleimportance: must knowfreq 70%

basics

~10 s

Add @AutoConfigureTestDatabase(replace = Replace.NONE) to keep your configured DataSource, and point the test at a real database — commonly a Postgres/MySQL container via Testcontainers instead of the default in-memory H2.

open as a page

Mechanically, what is a slice annotation like @DataJpaTest composed of? Name the two ingredients that make slicing work.

level: middleimportance: must knowfreq 62%

basics

~10 s

A slice annotation is a composed meta-annotation. It combines a @TypeExcludeFilter (to filter which beans get scanned) with one or more @AutoConfigure... annotations (to enable only that layer's auto-configuration).

open as a page

What does @RestClientTest do, and how do you assert against outgoing HTTP calls with MockRestServiceServer?

level: middleimportance: must knowfreq 55%

basics

~20 s

@RestClientTest is a slice for testing a component that calls a remote API via RestTemplate or RestClient. It auto-configures a MockRestServiceServer that intercepts outgoing requests, lets you set up expected requests and canned responses, and verifies they were called.

open as a page

In a @WebMvcTest, how do you provide the controller's service dependency, and what happens if you don't?

level: middleimportance: must knowfreq 74%

basics

~10 s

Add the missing dependency as a mock with @MockitoBean (older: @MockBean). Without it, the slice can't inject the controller's service and the context fails to start with a NoSuchBeanDefinitionException.

open as a page

What is @JsonTest and what does JacksonTester give you?

level: juniorimportance: should knowfreq 42%

basics

~20 s

@JsonTest is a Spring Boot slice for testing JSON serialization. It configures your app's Jackson (or Gson) setup and gives you a JacksonTester helper to serialize/deserialize objects and assert the resulting JSON, without starting the whole app.

open as a page

When would you choose @DataMongoTest over @SpringBootTest, and what are the trade-offs?

level: middleimportance: should knowfreq 45%

basics

~10 s

Use @DataMongoTest when you only test the persistence layer (repositories, MongoTemplate): it starts a smaller context, so tests are faster and more isolated. Use @SpringBootTest when behavior crosses layers or needs many beans.

open as a page

In @JdbcTest, how do the embedded database replacement and per-test rollback work, and how do you override them?

level: middleimportance: should knowfreq 38%

basics

~20 s

@JdbcTest swaps your DataSource for an in-memory DB (via @AutoConfigureTestDatabase, default Replace.ANY) and runs each test in a transaction that rolls back. Use Replace.NONE to keep your real datasource; use @Commit or @Rollback(false) to keep committed data.

open as a page

With @DataJpaTest on an embedded DB, how is the schema created, and how do Hibernate ddl-auto vs Flyway/Liquibase interact?

level: seniorimportance: should knowfreq 45%

basics

~10 s

By default the embedded DB gets its schema from Hibernate ddl-auto=create-drop (generated from your @Entity mappings). If Flyway or Liquibase is on the classpath, Spring Boot runs those migrations instead to build the schema.

open as a page

Why is @DataJpaTest faster than @SpringBootTest, and what exactly is excluded from the slice?

level: seniorimportance: should knowfreq 58%

basics

~10 s

@DataJpaTest only auto-configures JPA/persistence beans and disables full component scanning, so the context is small and starts fast. @SpringBootTest loads the entire application — controllers, services, security, web server — which is much heavier.

open as a page

Compare @DataMongoTest with its sibling data slices @DataR2dbcTest, @DataRedisTest, and @DataLdapTest. What does each wire, and what do they share?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Each is a Spring Boot slice that loads only its store's auto-config: @DataMongoTest → Mongo repos + MongoTemplate; @DataR2dbcTest → reactive relational (DatabaseClient/R2dbcEntityTemplate); @DataRedisTest → RedisTemplate + Redis repos; @DataLdapTest → LdapTemplate + LDAP repos. All exclude unrelated beans and disable general auto-config.

open as a page

How do you assert a JSON serialization round-trip with JacksonTester and JsonContent?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Serialize with json.write(obj) to get a JsonContent, then assert with extractingJsonPath...Value or isEqualToJson against an expected file. For the reverse, json.parseObject(text) turns JSON back into the object so you can assert its fields. Doing both proves a round-trip.

open as a page

Your @WebMvcTest needs an auto-configuration the slice doesn't include (say Spring Security's or a custom one). How do you add it without switching to @SpringBootTest?

level: seniorimportance: should knowfreq 55%

basics

~10 s

Add the specific auto-configuration back onto the slice. Use the relevant @AutoConfigureXxx annotation (e.g. one exists automatically), or @ImportAutoConfiguration(TheAutoConfiguration.class) to pull in exactly the auto-config classes you need — no full context required.

open as a page

When a slice enables 'only the relevant auto-configuration', where does that curated list physically come from, and how has it changed across Spring Boot versions?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Each @AutoConfigureXxx is backed by @ImportAutoConfiguration, which reads a fixed list of auto-config class names from a resource file — historically a key in META-INF/spring.factories, and in modern Boot a META-INF/spring/<annotation>.imports file.

open as a page

In MockRestServiceServer, how do you control expected call counts and request ordering, and test retries or multiple calls?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Use ExpectedCount in server.expect(...) — like once(), times(n), min(n), max(n), manyTimes(), never() — to say how many times a request should occur. By default expectations must happen in the order recorded; you can build an unordered server (ignoreExpectOrder) so requests match in any order, which is useful for retries or concurrent calls.

open as a page

How is WebTestClient bound in a @WebFluxTest, and how do you handle Spring Security in the slice?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In @WebFluxTest, WebTestClient binds directly to the in-memory WebFlux handler (no server/port), so tests are fast and deterministic. If Spring Security is on the classpath it also applies in the slice, so you use test security config or mutators like mockUser() to authenticate requests.

open as a page

With Spring Security on the classpath, a @WebMvcTest returns 401/403 unexpectedly. Why, and how do you handle it correctly?

level: seniorimportance: should knowfreq 55%

basics

~20 s

@WebMvcTest applies your Spring Security filter chain, so unauthenticated MockMvc requests get blocked. Fix it by authenticating the test request — e.g. @WithMockUser or SecurityMockMvcRequestPostProcessors — or by importing your security config, not by disabling security.

open as a page

When would you choose @WebMvcTest over @SpringBootTest, and what are the tradeoffs?

level: seniorimportance: should knowfreq 68%

basics

~10 s

Use @WebMvcTest for fast, isolated web-layer tests (routing, validation, JSON, error handling) with mocked services. Use @SpringBootTest when you need the full context — real service/repository wiring or true end-to-end integration.

open as a page

How do you decide between @WebFluxTest/@RestClientTest slices and a full @SpringBootTest, and what are the tradeoffs?

level: principalimportance: should knowfreq 25%

basics

~20 s

Use slices (@WebFluxTest, @RestClientTest) for fast, focused unit-ish tests of one layer with collaborators mocked. Use @SpringBootTest when you need the real wired application — cross-layer flows, real security, real transport, or integration with the database or a running server. Slices are cheaper but cover less.

open as a page

As a tech lead, how would you structure a codebase's persistence testing around @DataJpaTest — where it fits, its blind spots, and what complements it?

level: principalimportance: nice to knowfreq 30%

basics

~10 s

Use @DataJpaTest for fast, focused repository/query tests, but run them against a production-matching DB (Testcontainers, Replace.NONE) to avoid H2 fidelity gaps. Complement with a few full @SpringBootTest integration tests for cross-layer flows.

open as a page

Explain the mechanism that makes @DataMongoTest exclude your @Service beans, and how you'd customize a data slice (add auto-config, include a bean, change transaction behavior).

level: principalimportance: nice to knowfreq 20%

basics

~10 s

@DataMongoTest is meta-annotated with @OverrideAutoConfiguration(enabled=false) so only its listed auto-config runs, and a TypeExcludeFilter that filters out @Component/@Service/@Controller during scanning. To customize, use @Import, nested @TestConfiguration, extra @AutoConfigure... annotations, or @AutoConfigureDataMongo attributes.

open as a page

When should you choose @JdbcTest / @JsonTest over @SpringBootTest, and what are the design tradeoffs of test slices?

level: principalimportance: nice to knowfreq 24%

basics

~20 s

Use narrow slices like @JdbcTest and @JsonTest to test one layer fast and in isolation with a tiny context; use @SpringBootTest when you need the whole wired application (cross-layer integration, real beans). Slices trade fidelity and coverage for speed and focus.

open as a page

Design a custom test slice for your own infrastructure module, and explain how slice design interacts with the TestContext cache and suite performance.

level: principalimportance: nice to knowfreq 22%

basics

~10 s

Create a composed annotation mirroring Boot's: @BootstrapWith a bootstrapper (or reuse SpringBootTest's), @OverrideAutoConfiguration(enabled=false), a @TypeExcludeFilter for your beans, and @ImportAutoConfiguration listing your auto-config. Keep configurations uniform so the TestContext cache reuses contexts across tests.

open as a page

How does the @WebMvcTest slice actually decide which beans and auto-configurations to include, and how would you customize it?

level: principalimportance: nice to knowfreq 34%

basics

~10 s

@WebMvcTest is meta-annotated to restrict component scanning to web-layer stereotypes via a TypeExcludeFilter, and to enable only web-related auto-configurations listed in spring.factories/AutoConfiguration.imports. You customize it with controllers=, @Import, @AutoConfigure* annotations, or excludeAutoConfiguration.

open as a page