MockCertMockCert
Menu

Test yourself in exam conditions

A full Spring Certified Professional mock exam: 60 questions in 130 minutes, scored against the real exam's pass mark. Your first one is free.

Start a free mock exam
Domain 4 · 2 topics · about 13 minTopics in this domainTopics

Domain 4 · Overview

Overview

Up next: Testing Spring Applications · 11 steps + check · 6 min

Domain 4 · Topic 1 of 2

Testing Spring Applications

Step 1 of 11

Think first How do you give a Spring test the right beans, profiles and database state without slowing the suite down?

Why it matters: Questions describe a test setup and ask which annotation, profile or transaction behavior produces the stated result.

Spring tests load a real ApplicationContext without an application server and reuse it across the suite. Profiles decide which beans load, and each test's transaction rolls back unless you say otherwise.

Step 2 of 11

Term Meaning
TestContext framework Spring's test support that loads, caches and injects an application context, whatever test framework you use.
@ActiveProfiles Test class annotation listing the bean definition profiles to activate for the test context.
Default profile Profile whose beans load only when no other profile is specifically activated.
@Commit Makes a test's transaction commit instead of rolling back.
@TestConfiguration Nested configuration used in addition to the application's primary configuration.

Step 3 of 11

The TestContext framework works with JUnit, TestNG and others. It runs integration tests without an application server or other deployment environment. Once loaded, a test ApplicationContext is reused, so setup is paid once per suite. It can also inject beans into your test instances.

Exam trap The test context is not rebuilt before every test by default. It is loaded once and reused across the suite.

Step 4 of 11

@SpringJUnitConfig bundles the extension and context setup. It saves you from declaring two annotations on every test class. @SpringJUnitWebConfig adds web setup on top. @EnabledIf runs a test class or method only when its expression evaluates to true.

Two composed test annotations compared

Annotation JUnit Jupiter part Spring part
@SpringJUnitConfig @ExtendWith(SpringExtension.class) @ContextConfiguration
@SpringJUnitWebConfig @ExtendWith(SpringExtension.class) @ContextConfiguration and @WebAppConfiguration

Step 5 of 11

The default MOCK environment starts no embedded server. MOCK loads a web ApplicationContext with a mock web environment. DEFINED_PORT starts a real server on the port from application.properties, or on 8080 by default.

Exam trap With RANDOM_PORT or DEFINED_PORT, client and server run in separate threads. A @Transactional test cannot roll back a transaction started on the server.

Step 6 of 11

A nested @TestConfiguration adds to your main configuration. A nested @Configuration class would replace the primary configuration instead. Several @…Test slice annotations in one test are not supported. Pick one and add the other slices' @AutoConfigure… annotations by hand.

Step 7 of 11

@ActiveProfiles picks the profiles for the test context. List the profiles to activate when the test's ApplicationContext loads. Set inheritProfiles to stop inheriting a superclass's profiles. For logic, register a custom ActiveProfilesResolver through the resolver attribute.

Exam trap Setting spring.profiles.active as a JVM property or environment variable does not override @ActiveProfiles. The framework ignores that property when the annotation is present.

Step 8 of 11

Each test's transaction rolls back by default. The framework creates a transaction for every test and rolls it back afterward. It uses a PlatformTransactionManager bean from the test's application context. Add @Commit when a test should keep its changes.

Step 9 of 11

@Sql runs SQL scripts against a database in tests. Put it on a test class or a test method. The spring-jdbc module can configure and launch an embedded database for these tests. JdbcTestUtils adds static JDBC helper methods for common database test cases.

Step 10 of 11

@DataJpaTest scans entities and configures repositories. It also configures an embedded database when one is on the classpath. SQL queries are logged by default; turn this off with showSql. You can inject TestEntityManager, a test-focused alternative to the standard EntityManager.

Step 11 of 11

  • A loaded test context is reused, so setup runs once per test suite.
  • Test transactions roll back by default; use @Commit to keep the changes.
  • @ActiveProfiles on a test class wins over the spring.profiles.active property.
  • The default MOCK web environment does not start an embedded server.

Sources: Integration Testing :: Spring Framework (opens in a new tab) · Context Configuration with Environment Profiles :: Spring Framework (opens in a new tab) · Testing Spring Boot Applications :: Spring Boot (opens in a new tab) · Spring JUnit Jupiter Testing Annotations :: Spring Framework (opens in a new tab) · @ActiveProfiles :: Spring Framework (opens in a new tab) · @Sql :: Spring Framework (opens in a new tab) · JDBC Testing Support :: Spring Framework (opens in a new tab)

Check

Check: Testing Spring Applications

Cards to recall, then questions on this topic. About 2 minutes. Nothing is saved without an account.

Loading the cards and questions…

Up next: Advanced Testing with Spring Boot and MockMVC · 11 steps + check · 6 min

Domain 4 · Topic 2 of 2

Advanced Testing with Spring Boot and MockMVC

Step 1 of 11

Think first When should you test a controller with standalone MockMvc instead of loading your full Spring MVC configuration?

Why it matters: Questions describe a web test goal and ask which MockMvc setup, test annotation or bean override fits it.

MockMvc runs full Spring MVC request handling through mock requests, with no running server. You choose how much configuration it loads, from one controller to your whole MVC setup.

Step 2 of 11

Term Meaning
MockMvc Runs Spring MVC request handling with mock Servlet objects instead of a running server.
Standalone setup A MockMvc setup that points straight at chosen controllers and loads no Spring configuration.
@MockitoBean Swaps a bean in the test ApplicationContext for a Mockito mock.
@SpringJUnitConfig One annotation that combines the JUnit Jupiter SpringExtension with @ContextConfiguration.
@SpringBootTest Spring Boot's annotation for full end-to-end integration tests.

Step 3 of 11

Calling a controller directly skips most of Spring MVC. A plain unit test misses request mappings, data binding, message conversion, type conversion and validation. MockMvc fills that gap. It drives the DispatcherServlet with mock Servlet objects, so no server has to start.

Exam trap MockMvc does not start an embedded server. It replays full request handling with mock request and response objects.

Step 4 of 11

Load your MVC configuration, or point at controllers. The choice decides how much of your application each test covers. Loaded configuration is cached by the TestContext framework, which keeps a growing suite fast.

WebApplicationContext and standalone MockMvc setups compared

Feature WebApplicationContext Standalone
What it loads Your actual Spring MVC configuration No Spring configuration; one controller at a time
Dependencies Override services with @MockitoBean or @TestBean Inject mock dependencies into the controller by hand
Coverage A more complete integration test Needs extra integration tests for the MVC configuration

Exam trap A passing standalone test does not prove your Spring MVC configuration works. You still need integration tests for that.

Step 5 of 11

MockMvc sees inside request handling. Because these are server-side tests, you can assert which handler ran and whether a HandlerExceptionResolver handled an exception. You can also check the model and any binding errors. The MockHttpServletResponse keeps any forwarded or redirected URL, so you can assert it.

Step 6 of 11

Some servlet container behavior is missing. By default there is no context path and no jsessionid cookie. Forward, error and async dispatches do not happen, so JSPs are never rendered. To test with the full request URI, set contextPath and servletPath so mappings still match.

Exam trap Query parameters in the URI template get decoded, but values passed through param(...) are expected to be decoded already.

Step 7 of 11

andExpectAll(..) reports every failed expectation. Unlike andExpect(..), it asserts all the expectations you pass and tracks each failure. Common expectations set on the instance always apply; dropping them takes a separate MockMvc instance. The print() handler writes result data to System.out unless an unhandled exception occurs.

Step 8 of 11

@MockitoBean mocks a bean; @MockitoSpyBean spies on one. Both override a bean in the test's ApplicationContext. On a field, the bean is found by the field's type. A @Qualifier, or else the field name, picks between several candidates.

How the two bean override annotations behave

Feature @MockitoBean @MockitoSpyBean
Strategy REPLACE_OR_CREATE by default WRAP: spies on an early instance of the real bean
When no bean exists Creates a new bean Not allowed: exactly one candidate bean is required
Special beans A non-singleton bean becomes a singleton mock A scoped proxy cannot be spied on

Exam trap With enforceOverride = true, the mock replaces the bean directly. It is never wrapped in an AOP proxy, even when the original bean uses @Transactional.

Step 9 of 11

A loaded test context is reused by default. So the setup cost is paid only once per test suite. Qualifiers, including field names, decide whether a new context is needed. Name mock fields the same way across test classes to avoid extra contexts.

Step 10 of 11

@SpringJUnitConfig bundles the extension and context setup. It combines @ExtendWith(SpringExtension.class) with @ContextConfiguration, and @SpringJUnitWebConfig adds @WebAppConfiguration. These annotations, and various Spring Boot Test annotations, often register the SpringExtension for you. For full end-to-end tests, Spring Boot offers @SpringBootTest.

Step 11 of 11

  • Plain controller unit tests skip mappings, binding, conversion and validation; MockMvc covers them without a server.
  • Standalone MockMvc tests need extra integration tests to verify your Spring MVC configuration.
  • @MockitoBean replaces or creates a bean, while @MockitoSpyBean wraps exactly one existing bean.
  • Test contexts are cached and reused by default, so keep mock field names consistent across classes.

Sources: Overview :: Spring Framework (opens in a new tab) · MockMvc :: Spring Framework (opens in a new tab) · Setup Options :: Spring Framework (opens in a new tab) · @MockitoBean and @MockitoSpyBean :: Spring Framework (opens in a new tab) · Spring JUnit Jupiter Testing Annotations :: Spring Framework (opens in a new tab) · MockMvc vs End-to-End Tests :: Spring Framework (opens in a new tab) · Performing Requests :: Spring Framework (opens in a new tab) · Defining Expectations :: Spring Framework (opens in a new tab)

Check

Check: Advanced Testing with Spring Boot and MockMVC

Cards to recall, then questions on this topic. About 2 minutes. Nothing is saved without an account.

Loading the cards and questions…

Domain 4 · after the last topic

Domain 4 review

Each topic's Check tested it on its own; this mixes them.

Mixed quiz

Take the Domain 4 quiz

6 questions mixed from every topic in this domain, each answer explained. Mixing topics is harder than one at a time, and it is what the exam does. No account needed; with a free account your answers also build your estimated exam score.

Flashcards

Domain 4 flashcards

4 cards with this domain's key facts. Flip each one and check what you knew. No account needed.

Test yourself in exam conditions

A full Spring Certified Professional mock exam: 60 questions in 130 minutes, scored against the real exam's pass mark. Your first one is free.

Start a free mock exam
Next domain · 16% of topicsSecurity3 topics

Report a problem

On “”. Tell us what looks wrong; we read every report.

What is the problem?

Optional.