MockMvc
Spring Boot
testing
empty response
troubleshooting

Why does MockMvc always return empty content?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

MockMvc returning empty content usually means controller wiring, serialization, or test request setup is incomplete. The endpoint may execute but produce no body due to missing @ResponseBody, wrong media type expectations, or mocked dependencies returning null values.

Engineering guidance should support implementation and operations together. Clear assumptions, diagnostics, and fallback planning improve reliability under real traffic and evolving dependencies.

Diagnosing Empty MockMvc Responses

1. Verify Controller Response Semantics

Ensure controllers return response bodies through @RestController or @ResponseBody. Without that, view resolution may run instead of JSON serialization.

java
1@RestController
2@RequestMapping("/api/users")
3class UserController {
4    @GetMapping("/{id}")
5    public UserDto get(@PathVariable long id) {
6        return new UserDto(id, "Ana");
7    }
8}

Start with a minimal baseline and verify one known-good path first. This gives a stable reference before optimization or feature expansion.

2. Configure Test Context And Mocks Correctly

In web-slice tests, mocked service beans must return concrete objects. Null service outputs often serialize to empty bodies or no content responses.

java
1@WebMvcTest(UserController.class)
2class UserControllerTest {
3    @Autowired MockMvc mockMvc;
4    @MockBean UserService userService;
5
6    @Test
7    void returnsUser() throws Exception {
8        when(userService.find(1L)).thenReturn(new UserDto(1L, "Ana"));
9
10        mockMvc.perform(get("/api/users/1"))
11            .andExpect(status().isOk())
12            .andExpect(content().contentType("application/json"));
13    }
14}

After baseline correctness, harden around edge cases, error handling, and resource boundaries. Reliability gains usually come from this stage.

3. Inspect Actual Response Details

Print response body and headers in tests while debugging. Many empty-content issues are media-type mismatches or status-code differences rather than controller logic defects.

Add edge-case and failure-path checks to automated tests so future refactors preserve expected behavior. Keep test fixtures representative of production conditions when possible.

Operational safety should include rollback planning, focused telemetry, and ownership clarity. These practices reduce incident impact and improve release confidence.

A complete implementation plan should include clear ownership, expected operational signals, and maintenance procedures. Define who owns this part of the system, where alerts should route, and what a healthy baseline looks like in terms of latency, errors, and throughput. Ownership clarity significantly reduces resolution time when incidents involve cross-team dependencies.

Testing depth should go beyond happy paths. Add one representative production-like scenario, one malformed-input case, and one dependency-failure case with explicit assertions. Keep these checks automated and fast so they run on every change. Repeatable CI checks are the strongest guard against regressions introduced by dependency updates or large-scale refactors.

Observability should be intentional, not verbose. Log key branch decisions and include identifiers needed to trace a request or operation end to end. Track metrics tied to user impact, then compare post-release values against known baselines. This makes it easier to distinguish actual improvements from random variance.

Before rollout, prepare a rollback and fallback path. Feature flags, staged rollout, or known-safe previous versions can prevent prolonged outages when assumptions fail under real traffic. Recovery planning ahead of time is a core engineering practice, not an optional process artifact.

Finally, keep concise runbook notes close to the code. Updated documentation for validation steps and recovery actions saves substantial time during handoffs and on-call rotations.

Review post-release metrics within a fixed time window and capture outcomes in team notes for future change planning.

Common Pitfalls

  • Using @Controller without response body annotations in API tests.
  • Mocking service methods but returning null by default.
  • Asserting JSON content when endpoint actually returns no-content status.
  • Forgetting Jackson configuration in test slices that need custom serializers.
  • Ignoring request accept headers that influence content negotiation.

Summary

  • Use @RestController semantics for JSON endpoints under test.
  • Ensure mocked dependencies return concrete serializable objects.
  • Check status code and media type before asserting body content.
  • Inspect full response details to pinpoint negotiation issues.

Course illustration
Course illustration

All Rights Reserved.