springmvc 接口的测试方式 RestTemplate、MockMvc、 Swagger、postman

发布时间 2023-08-02 10:53:38作者: 花开如梦

springmvc 接口的测试方式有四种方式分别是RestTemplate、MockMvc、 Swagger、postman 

先把两个测试用的两个controler文件放这里

@RestController
@Api(value="用户MyControler",tags={"都是测试接口"})
@RequestMapping("/bootmvc")
public class MyControler {
    @Autowired
    public Myservice myservice;

    @RequestMapping("/selectall")
    public Result selectAll(){
        Map<Integer, User> integerUserMap = myservice.selectAll();
        return new Result(200,"查询成功",integerUserMap);
    }

    @RequestMapping("/selectbyid/{id}")
    public Result selectById(@PathVariable("id") Integer id){
        User user = myservice.selectById(id);
        return new Result(200,"查询成功",user);
    }

    @PostMapping("/insertuser")
    public Result insertUser(@RequestBody User user){
        String mes = myservice.insertUser(user)?"插入数据成功":"插入数据失败,数据已存在";
        System.out.println(myservice.selectAll());
        return new Result(200,mes,user);
    }

    @PostMapping("/updatauser/{id}")
    public Result updataUser(@PathVariable("id") Integer id, @RequestBody User user){
        user.setId(id);
        String mes = myservice.updateUser(user) ? "更新数据成功" : "更新数据失败";
        System.out.println(myservice.selectAll());
        return new Result(200, mes, user);
    }

}
json controler
@RestController
@RequestMapping("/helloworld")
public class HelloWorld {
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}
View Code
@Component
public class User {
    private Integer id;
    private String username;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public User() {
    }

    public User(Integer id, String username, String address) {
        this.id = id;
        this.username = username;
        this.address = address;
    }

    public User(String username, String address) {

        this.username = username;
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
User
public class Result {
    private Integer code;
    private String message;
    private Object object;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public Result() {
    }

    public Result(Integer code, String message, Object object) {
        this.code = code;
        this.message = message;
        this.object = object;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", object=" + object +
                '}';
    }
}
Result

 

方式一:RestTemplate

/**
 * 注意:RestTemplate会在底层通过jackson 转成json 格式发送,因此controler接收的时候,要在参数上使用注解 @RequestBody 进行标注
 */
@SpringBootTest
public class Test_RestTemplate {

    private static RestTemplate restTemplate = null;

    @BeforeEach
    public void befor(){
        restTemplate = new RestTemplate();
    }
    @Test
    public void testSelectbyid(){
        Result result = restTemplate.getForObject("http://localhost:8080/bootmvc/selectbyid/{id}", Result.class, 5);
        System.out.println(result);
    }
    @Test
    public void testSelectAll(){
        ResponseEntity<Result> forEntity = restTemplate.getForEntity("http://localhost:8080/bootmvc/selectall", Result.class);
        System.out.println(forEntity.getBody());
    }
    @Test
    public void testInsertUser(){
        User user = new User(5,"刘邦", "大泽乡");
        //Result result = restTemplate.postForObject("http://localhost:8080/bootmvc/insertuser", user, Result.class);
        ResponseEntity<Result> resultResponseEntity = restTemplate.postForEntity("http://localhost:8080/bootmvc/insertuser", user, Result.class);
        System.out.println(resultResponseEntity.getBody());
    }
    @Test
    public void updataUser(){
        User user = new User("刘邦", "河间");
        /**
         * 注意 rest风格传递数据:"http://localhost:8080/bootmvc/updatauser/{id}" 和 new HttpEntity<>(user)
         * 一起使用的时候,在controler接收时候 id并不会被自动合并user里,可能是因为user传的是json过去,不是通过modeview传递的原因
         */
        ResponseEntity<Result> exchange = restTemplate.exchange("http://localhost:8080/bootmvc/updatauser/{id}", HttpMethod.POST, new HttpEntity<>(user), Result.class, 5);
        System.out.println(exchange.getBody());
    }

}

常用接口

DELETE
delete
GET
getForObject
按照指定Class返回对象
getForEntity
返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
HEAD
headForHeaders
OPTIONS
optionsForAllow
POST
postForLocation
postForObject
PUT
put
any
支持任何请求方法类型
exchange
execute

 

方式二:MockMvc 这种方式的好处是可以不用启动服务器就可以测试接口

必须使用

@AutoConfigureMockMvc 进行 MockMvc mockMvc;的自动注入。
官网上的自定义mockmvc 总是连接不成功。暂时不知道怎么用,官网地址:https://docs.jcohy.com/docs/spring-framework/5.3.22/html5/zh-cn/testing.html#spring-mvc-test-framework
JsonPath 官网:https://goessner.net/articles/JsonPath/
 
//注意使用静态导入的方式
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

@SpringBootTest @AutoConfigureMockMvc
//专门用于做mockmvc的, 由spring-test提供, 依赖junit5, 如果没有该注解需要通过代码构建MockMvc class MyMockMvcTests { @Autowired MockMvc mockMvc; @Test void testSelectAll() throws Exception { //JsonPath 官网:https://goessner.net/articles/JsonPath/ this.mockMvc.perform( get("/bootmvc/selectall") .accept(MediaType.APPLICATION_JSON_UTF8_VALUE) ).andExpect(status().isOk()) //参考数据:Headers = [Content-Type:"application/json;charset=UTF-8"] .andExpect(header().stringValues("Content-Type","application/json;charset=UTF-8")) //参考数据:Body = {"code":200,"message":"查询成功","object":{"1":{"id":1,"username":"张三","address":"北京"},"2":{"id":2,"username":"李四","address":"天津"},"3":{"id":3,"username":"王五","address":"河北"},"4":{"id":4,"username":"赵六","address":"河南"}}} .andExpect( jsonPath("$.message").value("查询成功") ) .andExpect( jsonPath("$.object.length()").value(4) )//读取 .andExpect( jsonPath("$.object.['1'].username").value("张三")) //读取map值 .andDo(print()); } @Test void testHelloWorld() throws Exception { this.mockMvc.perform(get("/helloworld/hello").accept(MediaType.ALL_VALUE)) .andExpect(status().isOk()) .andExpect(content().string("hello"))//断言返回值是字符串 “hello” .andDo(print()); } }

 方式三:Swagger 用来自动生成接口文档

访问地址:http://localhost:8080/swagger-ui.html

pom依赖

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
            使用swagger2 需要添加配置,目前3.x版本的springboot 配置swagger2会报错,只能将spring版本降到2.7.14
                spring.mvc.pathmatch.matching-strategy=ant_path_matcher
        -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

配置:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springboot04_mocmvc.controler"))//需要生成接口文档的包路径
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("1.0")
                        .contact(new Contact("负责人信息","www.antifouling.cn","123@qq.com"))
                        .build());
    }
}

swagger2是通过注解进行接口说明的,此处就不一一列举了,参考文档:https://www.freesion.com/article/5148788995/

其他的用的时候请自行百度

方式四:使用类似 postman 这样的工具进行请求测试,请自行下载测试