Spring Boot + MockMvc 测试Controller Api接口

本文详细介绍了如何使用MockMvc进行Spring Boot Controller API的测试,包括MockMvc的作用、测试步骤,以及如何处理参数问题。通过@SpringBootTest、@AutoConfigureMockMvc等注解创建测试环境,使用MockMvcRequestBuilders构造请求,结合断言验证响应。
摘要由CSDN通过智能技术生成

本文参考 SpringBoot junit 测试 controller (MockMvc)Spring Boot干货系列:(十二)Spring Boot使用单元测试

MockMvc是什么

MockMvc是Spring Test提供的功能,可是实现对Controller层(API)做测试,也就是不必启动工程就能测试Controller接口。 
MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境。而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。

MockMvc在RESTful中的参数问题

使用Spring Boot + MockMVC 测试Spring MVC请求的步骤:

1.准备测试环境 
2.通过MockMvc执行请求,添加验证断言 ,添加结果处理器,得到MvcResult进行自定义断言/进行下一步的异步请求
3.卸载测试环境

有以下controller需要测试

package com.example.junittestdemo;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.format.InputAccessor.Std;

@RestController
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@GetMapping("/findAll")
	public ResponseEntity findAll() throws IOException {
		List<Student> students = studentService.findAll();
		Studen
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值