You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring REST API:404与415自定义JSON响应在Postman可见但MockMVC测试无法获取的问题

Why MockMVC Doesn't Capture Your Custom 404/415 JSON Responses

Let's break down why you're seeing this discrepancy between MockMVC and TestRestTemplate, and how to fix it.

The Root Cause for 404 (NoHandlerFoundException)

When you use MockMVC, it doesn't automatically respect the spring.mvc.throw-exception-if-no-handler-found=true property you set in application.properties. By default, MockMVC's underlying DispatcherServlet doesn't throw NoHandlerFoundException when no request handler matches — it just returns a 404 status directly, skipping your @ControllerAdvice exception handler entirely.

That’s why your status code assertion passes, but the JSON content is missing: MockMVC isn’t triggering your custom error response logic for the 404 case.

Fix for 404 Testing with MockMVC

You need to explicitly configure MockMVC to enable the throwExceptionIfNoHandlerFound behavior in its DispatcherServlet. Here are two straightforward ways to do this:

Option 1: Customize MockMVC During Setup

When initializing MockMVC in your test class, use webAppContextSetup and add a dispatcher servlet customizer:

@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@BeforeEach
void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
            .addDispatcherServletCustomizer(dispatcherServlet -> 
                dispatcherServlet.setThrowExceptionIfNoHandlerFound(true))
            .build();
}

Option 2: Use a Test Configuration Bean

If you’re using @AutoConfigureMockMvc, create a test-specific configuration bean to set this behavior globally:

@TestConfiguration
public class MockMvcCustomConfig {
    @Bean
    public DispatcherServletCustomizer dispatcherServletCustomizer() {
        return servlet -> servlet.setThrowExceptionIfNoHandlerFound(true);
    }
}

Then import this config into your test class:

@SpringBootTest
@AutoConfigureMockMvc
@Import(MockMvcCustomConfig.class)
public class YourControllerTests {
    // Your test methods here
}

Checking the 415 (UnsupportedMediaTypeStatusException) Case

For the 415 error, ensure your MockMVC test actually sends a request with an unsupported media type to trigger the exception. For example, if your endpoint expects application/json, send a request with text/plain:

@Test
@Order(2)
public void unsupportedMediaTypeTest() throws Exception {
    mockMvc.perform(post("/user/login")
                    .contentType(MediaType.TEXT_PLAIN)
                    .content("invalid content"))
            .andExpect(status().isUnsupportedMediaType())
            .andExpect(jsonPath("$.message", is("Wrong request media type.")));
}

If you weren’t specifying an incorrect media type before, MockMVC wouldn’t hit your custom exception handler, leading to the same missing JSON issue.

Verify the Fix

After applying the DispatcherServlet customizer for 404, your original test should work as expected:

@Test
@Order(1)
public void endpointNotFound() throws Exception {
    mockMvc.perform(post("/user/logi"))
            .andExpect(status().isNotFound())
            .andExpect(jsonPath("$.message", is("Endpoint not found.")));
}

This ensures MockMVC behaves consistently with your running application, triggering your @ControllerAdvice handlers just like TestRestTemplate does.

内容的提问来源于stack exchange,提问作者Kovo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:27:44