使用 @webmvctest 注解可以只测试 controller 层,它会自动配置 mockmvc 并仅加载 web 相关的 bean。在测试类上添加该注解后,spring boot 会启动一个轻量级的 mvc 测试环境,无需启动完整的 web 服务器或加载 service、repository 等深层依赖。通过 @mockbean 模拟业务逻辑层的返回结果,即可专注于验证请求映射、参数绑定和响应数据。

如何配置测试类以隔离 Controller?
在测试类上使用 @WebMvcTest 并指定要测试的 Controller 类,同时使用 @MockBean 声明依赖的服务接口。这样 Spring 容器只会实例化指定的 Controller,而将 Service 替换为 Mockito 的模拟对象。开发者可以直接调用 mockMvc.perform() 发送 HTTP 请求,并断言状态码和 JSON 响应内容,从而实现对 Controller 逻辑的独立单元测试。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.bean.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
when(userService.getUser(1L)).thenReturn(new User(1L, "Alice"));
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}
如何处理 Controller 中的异常和全局配置?
@WebMvcTest 默认不会加载 @Configuration 类,但会扫描 @ControllerAdvice 和 @ExceptionHandler。如果 Controller 依赖自定义的 Converter 或 Formatter,需要手动在测试类中通过 @Import 引入这些配置类。对于全局异常处理,确保在测试中抛出预期异常,并使用 andExpect(ResultMatcher) 验证错误响应格式,这样可以保证异常处理逻辑与 Controller 解耦后的正确性。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.bean.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(UserController.class)
@Import(CustomConverter.class) // 导入必要的转换器
class UserControllerExceptionTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldHandleNotFound() throws Exception {
when(userService.getUser(999L)).thenThrow(new RuntimeException("Not Found"));
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"id\": 999}"))
.andExpect(status().isInternalServerError());
}
}
当 Service 返回空值时 Controller 如何响应?
当 @MockBean 模拟的 Service 方法返回 null 或空集合时,Controller 通常会根据业务逻辑决定是返回 404 还是空 JSON 对象。在测试中,可以通过 when(...).thenReturn(null) 设置模拟行为,然后使用 jsonPath 断言响应体中是否包含预期的字段或是否为空。这有助于验证 Controller 对边界条件的处理能力,确保前端能接收到一致的数据结构。

















