您当前的位置: 首页 > 

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用RestTemplate 测试Controller接口

梁云亮 发布时间:2020-06-11 19:40:56 ,浏览量:2

理论基础

TestRestTemplate是用于Restful请求的模版。 TestRestTemplate主要用于测试url请求后返回来的结果 RestTemplate 默认使用 jackson 完成 json 序列化和反序列化.

示例: 第一步:Maven依赖:

    org.springframework.boot
    spring-boot-starter-test
    test


    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-thymeleaf


    com.fasterxml.jackson.core
    jackson-databind


    junit
    junit

第二步:yml的配置信息
spring:
  #前缀,也就是模板存放的路径
  thymeleaf:
    prefix: classpath:/templates/
    #编码格式
    encoding: UTF-8
    #关闭缓存,不然无法看到实时页面
    cache: false
    #后缀
    suffix: .html
    #设置不严格的html
    mode: HTML
    servlet:
      content-type: text/html
第三步:代码框架
  • Controller
@Controller
@RequestMapping("/dept")
public class DeptController {
}
  • ControllerTest
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DeptControllerTests {
    @Autowired
    private TestRestTemplate restTemplate;
}
第四步:分别在Controller中写接口,在ControllerTest中写测试代码 Get 字符串
@ResponseBody
@RequestMapping("/demo11")
public String demo11() {
    return "sales";
}

测试代码:

@Test
public void test11() {
    ResponseEntity entity = restTemplate.getForEntity("/dept/demo11", String.class);
    System.out.println(entity.getStatusCode());
    System.out.println(entity.getBody());
}
Get页面
@RequestMapping("/demo12")
public String demo12() {
    return "index";
}

在resources/templates下创建index.html

DOCTYPE html>


    
    Title


    index


测试代码:

@Test
public void test12() {
    ResponseEntity entity = restTemplate.getForEntity("/dept/demo12", String.class);
    System.out.println(entity.getStatusCode());
    System.out.println(entity.getBody());
}
Get带参数,返回对象
@ResponseBody
@GetMapping("/demo13")
public Dept demo13(String dname) {
    Dept dept = new Dept();
    dept.setDname(dname);
    return dept;
}

测试代码:

@Test //获取简单POJO对象
public void test13() throws Exception {
    Map map = new HashMap();
    map.put("ddd", "sales");//传值,但要在url上配置相应的参数
    Dept result = restTemplate.getForObject("/dept/demo13?dname={ddd}", Dept.class, map);
    System.out.println(result);
}
Get带参数,返回对象
@ResponseBody
@GetMapping(value = "/demo14")
public Dept demo14(@RequestParam("dname") String dname) {
    Dept dept = new Dept();
    dept.setDname(dname);
    return dept;
}

测试代码:

@Test //获取简单POJO对象
public void test14() throws Exception {
    Map multiValueMap = new HashMap();
    multiValueMap.put("name", "sales");//传值,但要在url上配置相应的参数
    Dept result = restTemplate.getForObject("/dept/demo14?dname={name}", Dept.class, multiValueMap);
    System.out.println(result);
}
POST带参数,返回对象
@ResponseBody
@PostMapping("/demo21")
public Dept demo21(String dname) {
    Dept dept = new Dept();
    dept.setDname(dname);
    return dept;
}

测试代码:

@Test //获取简单POJO对象
public void test21() throws Exception {
    MultiValueMap multiValueMap = new LinkedMultiValueMap();
    multiValueMap.add("dname", "sales");
    multiValueMap.add("loc","china");
    Dept result = restTemplate.postForObject("/dept/demo21", multiValueMap, Dept.class);
    System.out.println(result);
}
POST带参数,返回对象
@ResponseBody
@RequestMapping("/demo222")
public Dept demo222(String dname, String loc) {
    Dept dept = new Dept();
    dept.setDname(dname);
    dept.setLoc(loc);
    return dept;
}

测试代码:

@Test //获取简单POJO对象
public void test222() {
    MultiValueMap map = new LinkedMultiValueMap();
    map.set("dname", "sales");
    map.set("loc", "china");

    Dept dept = restTemplate.postForObject("/dept/demo222", map, Dept.class);
    System.out.println(dept);
}
POST带参数,返回对象
@ResponseBody
@PostMapping("/demo221")
public Dept demo22(Dept dept) { //参数是一个对象
    return dept;
}

测试代码:

@Test //获取简单POJO对象
public void test221() {
    //此处不能使用Map=HashMap,否则值传递不到Controller
    MultiValueMap map = new LinkedMultiValueMap();
    map.set("dname", "sales");
    map.set("loc", "china");
    Dept entity = restTemplate.postForObject("/dept/demo221", map, Dept.class);
    System.out.println(entity);
}
Post返回List
@ResponseBody
@PostMapping("/demo23")
public List demo23() {
    List res = new ArrayList();
    res.add(new Dept(11, "aa", "aaaaa"));
    res.add(new Dept(22, "bb", "bbbbb"));
    res.add(new Dept(11, "cc", "ccccc"));
    return res;
}

测试代码:

@Test
public void test23() {
    ParameterizedTypeReference responseType = 
	new ParameterizedTypeReference() { };
    ResponseEntity responseEntity =
            restTemplate.exchange("/dept/demo23", HttpMethod.POST, null, responseType);
    List deptList = responseEntity.getBody();
    for (Dept dept : deptList) {
        System.out.println(dept);
    }
}
Get请求,返回对象
  • 返回数据:
{
    "deptList": [
        {
            "deptno": 11,
            "dname": "aa",
            "loc": "aaaaa"
        },
        {
            "deptno": 22,
            "dname": "bb",
            "loc": "bbbbb"
        }
    ]
}
  • DeptList
public class DeptList {
    private List deptList;
    public DeptList() {
        deptList = new ArrayList();
    }
    public List getDeptList() {
        return deptList;
    }
    public void setDeptList(List deptList) {
        this.deptList = deptList;
    }
}
  • Request
@ResponseBody
@GetMapping("/demo24")
public DeptList demo24() {
    List temp = new ArrayList();
    temp.add(new Dept(11, "aa", "aaaaa"));
    temp.add(new Dept(22, "bb", "bbbbb"));
    temp.add(new Dept(11, "cc", "ccccc"));
    DeptList deptList = new DeptList();
    deptList.setDeptList(temp);
    return deptList;
}
  • 测试代码:
@Test
public void test24() {
    DeptList deptList = restTemplate.getForObject("/dept/demo24",  DeptList.class);
    System.out.println(deptList);
    for (Dept dept : deptList.getDeptList()) {
        System.out.println(dept);
    }
}
Get请求,返回对象
  • 数据
{
    "code": 200,
    "data": [
        {
            "deptno": 11,
            "dname": "aa",
            "loc": "aaaaa"
        },
        {
            "deptno": 22,
            "dname": "bb",
            "loc": "bbbbb"
        }
    ],
    "msg": "success"
}
  • Result
public class Result {
    private Integer code;    //返回码
    private String msg;    //返回消息
    private T data;    //返回数据

    //…… getter/setter、toString()
}
  • Request
@ResponseBody
@GetMapping("/demo25")
public Result demo25() {
    List deptList = new ArrayList();
    deptList.add(new Dept(11, "aa", "aaaaa"));
    deptList.add(new Dept(22, "bb", "bbbbb"));
    deptList.add(new Dept(11, "cc", "ccccc"));

    Result res = new Result();
    res.setData(deptList);
    res.setCode(200);
    res.setMsg("success");
    return res;
}
  • 测试代码:
@Test
public void test25() {
    Class resClass = new Result().getClass();
    Result res = restTemplate.getForObject("/dept/demo25", resClass);
    System.out.println(res);

    System.out.println(res.getCode());
    System.out.println(res.getMsg());
    List data = res.getData();
    System.out.println(data);

    for (LinkedHashMap item : data) {
        System.out.println(item.get("deptno")+" "+item.get("dname")+" "+item.get("loc"));
    }
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0424s