当前位置: 移动技术网 > IT编程>开发语言>Java > 详解SpringBoot restful api的单元测试

详解SpringBoot restful api的单元测试

2019年07月19日  | 移动技术网IT编程  | 我要评论

现在我们来利用spring boot来构建一个restful api,具体如下:

1.添加springboot测试注解

@runwith(springrunner.class)
@springboottest
public class usercontrollertest {
}

2.伪造mvc环境

 // 注入spring 工厂
  @autowired
  private webapplicationcontext wac;
 //伪造mvc环境
  private mockmvc mockmvc;
  @before
  public void setup(){
    mockmvc = mockmvcbuilders.webappcontextsetup(wac).build();
  }

3.引入静态方法

import static org.springframework.test.web.servlet.request.mockmvcrequestbuilders.get;
import static org.springframework.test.web.servlet.request.mockmvcrequestbuilders.post;
import static org.springframework.test.web.servlet.request.mockmvcrequestbuilders.put;
import static org.springframework.test.web.servlet.request.mockmvcrequestbuilders.delete;
import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.jsonpath;
import static org.springframework.test.web.servlet.result.mockmvcresultmatchers.status;

3.编写测试方法

@test
  public void whenxxxxsuccess() throws exception {
    //模拟发送请求
    string result =
    mockmvc.perform(get("/user") //发往/user的get请求,可以换成post,put,delete方法执行相应请求
            .param("username","xxx") //get请求时填写参数的位置
            .contenttype(mediatype.application_json_utf8) //utf编码
            .content(content)) //post和put请求填写参数的位置
        .andexpect(status().isok())
        .andexpect(jsonpath("$.length()").value(3)) //期望的json返回结果
        .andreturn().getresponse().getcontentasstring(); //对返回字符串的json内容进行判断
    log.info(result);
  }

这里是具体的jsonpath语法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网