Spring Boot 单元测试 @WebMvcTest 对 Controller 进行单独测试
Spring Boot 单元测试 大约 2352 字需求
只能Controller
中的逻辑进行单元测试,Service
层不进行测试。
@MockBean
使用@MockBean
模拟Service
层,给定Service
层返回,人为控制Service
层的返回值。
@WebMvcTest
需要单元测试的Controller
类。指定一个需要测试的Controller
类。
Controller 类
@Slf4j
@RestController
public class HiController {
@Resource
private HelloService helloService;
@GetMapping("/hi")
public Response hiGet(@RequestHeader("token") String token, @RequestParam("username") String username, HttpServletRequest request) {
log.info("hello token#{}, username#{}, request#{}", token, username, request);
Response response = helloService.sayHello(1);
return response;
}
@PostMapping("/hi")
public Response hiPost(@Valid @RequestBody HelloRequest request) {
log.info("helloPost request#{}", request);
return Response.builder().msg(request.getCode()).build();
}
}
单元测试类
@WebMvcTest(HiController.class)
class HiControllerTests {
@Autowired
MockMvc mockMvc;
@MockBean
HelloService helloService;
@Test
@DisplayName("测试 GetMapping 接口")
void testGetMappingWithMockMvc() throws Exception {
BDDMockito.given(helloService.sayHello(1))
.willReturn(Response.builder().msg("response msg").build());
mockMvc.perform(MockMvcRequestBuilders.get("/hi")
.header("token", "test-token")
.param("username", "test-username")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.content().string(containsString("msg")))
.andReturn();
}
@Test
@DisplayName("测试 PostMapping 接口")
void testPostMappingWithMockMvc() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/hi")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"code\":\"ddd-d\",\"name\":\"this is name\"}")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("code").value(0))
.andReturn();
}
}
参考
阅读 853 · 发布于 2022-10-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Nginx 使用 Basic Auth 认证做资源访问限制阅读 3115
-
微信小程序基于 Parser 添加长按复制、代码高亮等功能阅读 4568
-
IDEA Debug Method Breakpoint 方法断点影响启动速度阅读 800
-
Java 中的锁 ReentrantReadWriteLock 读写锁阅读 1453
-
Nginx 配置静态文件 404(root 与 alias 区别)阅读 5554
-
IDEA 调试 Java 多线程代码阅读 1464
-
Spring Boot @ComponentScan exclude 不起作用阅读 1225
-
Java jcmd 代替 jmap 导出堆内存快照阅读 2152
-
OpenResty lua-resty-auto-ssl 无法颁发证书问题阅读 2122
-
ThinkPHP5 设置数据库长连接阅读 4408