Boot Testing, MockMVC & Slice Tests practice questions

From Spring Certified Professional (Develop) (2V0-72.22) · 33 questions on this topic

Boot Testing, MockMVC & Slice Tests practice questions from Spring Certified Professional (Develop) (2V0-72.22). This pack has 33 questions tagged Boot Testing, MockMVC & Slice Tests, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Boot Testing, MockMVC & Slice Tests

  1. Question 1

    Which TWO statements correctly distinguish @MockBean from @SpyBean in a Spring Boot slice test? Select TWO.

    1. A. @MockBean adds or replaces a matching bean with a Mockito mock whose methods you stub with given(...).willReturn(...).Correct answer

      @MockBean contributes a Mockito mock, replacing any existing matching bean or adding one, and its behaviour is defined by stubbing rather than by real method calls.

    2. B. @SpyBean wraps the real bean so its real methods execute unless stubbed, which is useful for verifying interactions on the genuine implementation.Correct answer

      @SpyBean is a Mockito spy over the actual bean: real methods run by default and can be selectively stubbed, so you can verify interactions against the real object.

    3. C. @SpyBean produces a bean whose every method returns null or a default until you stub it, exactly like a plain mock.

      That describes a mock, not a spy; a spy invokes the real methods unless a stub overrides them, so it does not return defaults everywhere by default.

    4. D. Neither @MockBean nor @SpyBean affects the context cache, so the cached context is reused unchanged.

      Both annotations mutate the context by inserting a mock or spy, which resets/evicts the cached context, so the claim that the cache is untouched is wrong.

    5. E. @MockBean can only add a brand-new bean and can never replace an existing bean of the same type.

      @MockBean will replace an existing matching bean when one is present, not merely add new beans, so this restriction is false.

    Explanation

    @MockBean installs a Mockito mock — replacing a matching bean or adding one — whose behaviour comes entirely from stubbing, whereas @SpyBean wraps the real bean so its real methods run unless overridden, which is what lets you verify interactions on the genuine implementation. A spy is not a default-returning mock, both annotations reset the context cache because they alter the context, and mock beans can replace existing beans rather than only adding new ones.

  2. Question 2

    You want a @SpringBootTest to load the full context but with the property app.feature.enabled set to false for that test class only, without editing any properties file. Which use of @SpringBootTest expresses this?

    1. A. @SpringBootTest(classes = "app.feature.enabled=false")

      The classes attribute takes configuration/component classes, not property key-value strings, so this would not compile and does not set any property.

    2. B. @SpringBootTest(properties = "app.feature.enabled=false")Correct answer

      The properties attribute of @SpringBootTest adds inlined properties to the test's Environment with high precedence, overriding the value for that test class only.

    3. C. @SpringBootTest(webEnvironment = "app.feature.enabled=false")

      webEnvironment selects the web environment enum (MOCK/RANDOM_PORT/etc.); it does not accept property assignments.

    4. D. @SpringBootTest(profiles = "app.feature.enabled=false")

      @SpringBootTest has no profiles attribute, and profiles select bean-definition groups rather than assign individual property values; activating profiles is done with @ActiveProfiles.

    Explanation

    @SpringBootTest exposes a properties attribute that inlines key-value pairs into the test's Environment at high precedence, so a single property can be overridden for just that test class without touching a properties file. The configuration-classes and web-environment attributes serve unrelated purposes, and there is no profiles attribute on the annotation — profile activation is a separate concern handled elsewhere.

  3. Question 3

    A failing MockMvc test needs to log the full request and response (method, URI, headers, body, resolved handler) to the console for debugging. Which addition to the perform chain does this?

    1. A. Wrap the whole call in System.out.println(...).

      Printing the MvcResult object itself yields an opaque toString, not the structured request/response dump MockMvc can produce; it does not surface the handler, headers, and body in readable form.

    2. B. .andDo(print())Correct answer

      andDo(print()) applies the MockMvcResultHandlers.print() handler, which writes the full request and response details — method, URI, headers, body, and resolved handler — to the console.

    3. C. .andExpect(print())

      andExpect takes a ResultMatcher for assertions; print() is a ResultHandler and does not belong there, so this would not compile.

    4. D. Enable @AutoConfigureMockMvc(printOnlyOnFailure = true) and nothing else.

      That attribute governs automatic printing configuration but is not how you attach the print handler to a specific perform chain; the explicit result handler is the direct mechanism, and this option omits it.

    Explanation

    MockMvc exposes result handlers through the andDo step, and the print handler dumps the full request and response — method, URI, headers, body, and resolved handler — to the console. Assertions go through andExpect with matchers, so a handler cannot be placed there, and simply printing the result object gives no structured detail.

  4. Question 4

    A team writes a test annotated with `@SpringBootTest` plus `@AutoConfigureMockMvc` and injects `MockMvc`. A reviewer claims the test is meaningless because "MockMvc never runs the real controller". What actually happens when a request is performed through a `MockMvc` instance configured this way?

    1. A. The full Spring MVC infrastructure — DispatcherServlet, handler mapping, the real controller, argument resolvers, and view/message conversion — is exercised in-process, but no HTTP connection or servlet container is started.Correct answer

      This is exactly what MockMvc provides: full Spring MVC request handling driven from mock servlet objects, without a running container or network socket, which is why Boot's MockMvc-based tests are fast yet still exercise the whole web layer (Spring Boot reference, Auto-configured Spring MVC Tests).

    2. B. The controller bean itself is replaced by a Mockito mock, so only the URL-to-handler mapping is verified while the handler body never executes.

      Confuses the word 'mock' in MockMvc with mocking the controller. MockMvc mocks the servlet environment (request/response/servlet context), not the handler; the real controller method body runs.

    3. C. An embedded servlet container is started on a random port and the request is sent over real HTTP to that port.

      Describes `@SpringBootTest(webEnvironment = RANDOM_PORT)` with a real client such as TestRestTemplate/WebTestClient. MockMvc deliberately avoids starting a container or opening a socket.

    4. D. Only the serialization of the request and response bodies is tested; handler mappings, filters, and exception handlers are bypassed entirely.

      Confuses MockMvc with the JSON marshalling slice (`@JsonTest`/`JacksonTester`). MockMvc dispatches through the full MVC pipeline, including registered filters and exception handling.

    Explanation

    MockMvc drives Spring MVC through the DispatcherServlet using mock servlet request and response objects, so handler mapping, the real controller method, argument resolution, message conversion, filters, and exception handling all execute — but no servlet container starts and no HTTP socket is opened. That is why it is neither a unit test of an isolated controller nor a live HTTP integration test. Believing the controller is stubbed confuses mocking the servlet environment with mocking the bean; believing a port is opened describes the RANDOM_PORT web environment used with a real client; believing only body marshalling is checked describes the JSON test slice instead.

  5. Question 5

    How does TestRestTemplate differ from MockMvc?

    1. A. TestRestTemplate is for unit tests that load no context

      TestRestTemplate is used in integration tests that load an application context and start a server, not context-less unit tests.

    2. B. TestRestTemplate never touches the network either

      TestRestTemplate does make real network calls to the running embedded server; that is precisely how it differs from MockMvc's in-process invocation.

    3. C. TestRestTemplate makes real HTTP calls to a running embedded server, whereas MockMvc invokes the MVC stack in-process without a serverCorrect answer

      TestRestTemplate is paired with a started server (e.g. RANDOM_PORT) to exercise the app over real HTTP, while MockMvc drives the dispatcher servlet directly without any networking.

    4. D. TestRestTemplate only tests the service layer

      TestRestTemplate exercises the full running application over HTTP end to end, not just the service layer in isolation.

    Explanation

    TestRestTemplate is used against a started embedded server (e.g. with RANDOM_PORT) to exercise the application over real HTTP through the actual network, whereas MockMvc invokes the dispatcher servlet directly in-process with no networking. Both operate within a loaded application context, so the distinction is real-HTTP integration versus in-process MVC invocation, not unit versus integration or service-layer-only testing.

  6. Question 6

    Which TWO statements correctly describe `TestRestTemplate` as used in Spring Boot integration tests? (Select all that apply.)

    1. A. It is auto-configured as a bean only when `@SpringBootTest` runs with a `webEnvironment` that starts an embedded server (RANDOM_PORT or DEFINED_PORT).Correct answer

      Correct: Spring Boot auto-configures a TestRestTemplate for injection only when a real servlet container has been started, since the template needs a live port to talk to.

    2. B. By default it does not throw an exception for 4xx or 5xx responses; the error status is returned in the `ResponseEntity` for the test to assert on.Correct answer

      Correct: TestRestTemplate is fault-tolerant by comparison with RestTemplate — it does not apply the default error handler that raises exceptions, so tests can assert directly on error status codes.

    3. C. It bypasses the network stack and dispatches requests directly to the `DispatcherServlet`, so no embedded container is required.

      Confuses TestRestTemplate with MockMvc. MockMvc performs a mock dispatch without a socket; TestRestTemplate issues genuine HTTP requests over a real port.

    4. D. It automatically rolls back any database changes made by the server-side code at the end of each test method.

      Confuses the HTTP client with @Transactional test rollback. Even with @Transactional, a request handled on a separate server thread runs in its own transaction and is not rolled back by the test's transaction.

    Explanation

    `TestRestTemplate` is a real HTTP client, so Spring Boot only auto-configures it for injection when the test has actually started an embedded server; it also deliberately suppresses the exception-throwing error handler so that a 404 or 500 comes back as a `ResponseEntity` the test can assert on. Dispatching straight into the `DispatcherServlet` without a socket is the behaviour of `MockMvc`, a different tool for the mock web environment. Automatic rollback comes from transactional test support, not from the client, and it does not reach work performed on the server's own request thread over a real HTTP connection.

  7. Question 7

    Which TWO statements about MockMvc are correct? Select TWO.

    1. A. It exercises the full Spring MVC stack — request mapping, filters, message converters, and validation — without starting a real HTTP server.Correct answer

      MockMvc dispatches through the DispatcherServlet in-process, so mapping, filters, converters, and validation all run, but no real network server is started.

    2. B. It is auto-configured either by @WebMvcTest or by adding @AutoConfigureMockMvc to a @SpringBootTest.Correct answer

      @WebMvcTest auto-provides a MockMvc, and on a full-context @SpringBootTest you opt in with @AutoConfigureMockMvc; both are documented ways to obtain a MockMvc.

    3. C. It requires an embedded servlet container listening on a real port to handle each request.

      MockMvc performs an in-process mock dispatch and binds no port; requiring a real listening container describes running-server clients like TestRestTemplate instead.

    4. D. It is the reactive test client used to exercise Spring WebFlux endpoints.

      The reactive, non-blocking test client for WebFlux is WebTestClient; MockMvc targets the servlet-stack Spring MVC.

    5. E. It bypasses controllers entirely and asserts directly against service-layer beans.

      MockMvc drives requests through the actual controllers via the dispatcher; it does not skip them to assert on services directly.

    Explanation

    MockMvc runs the whole servlet-side MVC pipeline — mapping, filters, converters, and validation — through an in-process dispatch with no real server, and a MockMvc instance is obtained either from the web slice or by adding the MockMvc auto-configuration to a full-context test. It does not need a listening container, it is not the reactive WebFlux client, and it invokes the real controllers rather than bypassing them to reach services.

  8. Question 8

    What does @WebMvcTest(UserController.class) load into the test context?

    1. A. Only the web slice — MVC infrastructure, the specified controller, and an auto-configured MockMvc; service/repository beans are NOT loaded and are typically provided via @MockBeanCorrect answer

      Correct: @WebMvcTest is a slice that configures the MVC infrastructure, the named controller, and an auto-configured MockMvc, while leaving @Service/@Repository beans out of the context so you supply them with @MockBean.

    2. B. Only JPA repositories and an embedded database

      Wrong: loading only JPA repositories and an embedded database describes the @DataJpaTest slice, not the web slice that @WebMvcTest configures.

    3. C. Nothing different from @SpringBootTest; it is just an alias

      Wrong: @WebMvcTest is not an alias for @SpringBootTest; it deliberately loads a narrow web slice rather than the full application context.

    4. D. The entire application context, including all services and repositories

      Wrong: loading the entire context with all services and repositories is what @SpringBootTest does; the whole point of @WebMvcTest is to narrow the context to the web layer.

    Explanation

    @WebMvcTest is a targeted slice that stands up only the Spring MVC infrastructure, the specified controller, and an auto-configured MockMvc. Service and repository beans are intentionally excluded from the context and are usually supplied as @MockBean, which keeps the test focused and fast. This is narrower than bootstrapping the full application context and distinct from the JPA-focused slice used for repository tests.

Practise all 33 Boot Testing, MockMVC & Slice Tests questions

Spring Certified Professional (Develop) has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open Spring Certified Professional (Develop)

Other topics in this pack