SpringBoot 使用TestRestTemplate 测试Controller接口

理论基础

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

示例:

第一步:Maven依赖:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
dependency>
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
dependency>

第二步: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<String> 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


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h2>indexh2>
body>
html>

测试代码:

@Test
public void test12() {
    ResponseEntity<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<Dept> demo23() {
    List<Dept> 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<List<Dept>> responseType = 
	new ParameterizedTypeReference<List<Dept>>() { };
    ResponseEntity<List<Dept>> responseEntity =
            restTemplate.exchange("/dept/demo23", HttpMethod.POST, null, responseType);
    List<Dept> 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<Dept> deptList;
    public DeptList() {
        deptList = new ArrayList<>();
    }
    public List<Dept> getDeptList() {
        return deptList;
    }
    public void setDeptList(List<Dept> deptList) {
        this.deptList = deptList;
    }
}
  • Request
@ResponseBody
@GetMapping("/demo24")
public DeptList demo24() {
    List<Dept> 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<T> {
    private Integer code;    //返回码
    private String msg;    //返回消息
    private T data;    //返回数据

    //…… getter/setter、toString()
}
  • Request
@ResponseBody
@GetMapping("/demo25")
public Result demo25() {
    List<Dept> 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<? extends Result> resClass = new Result<List<LinkedHashMap<String, Object>>>().getClass();
    Result<List<LinkedHashMap<String,Object>>> res = restTemplate.getForObject("/dept/demo25", resClass);
    System.out.println(res);

    System.out.println(res.getCode());
    System.out.println(res.getMsg());
    List<LinkedHashMap<String,Object>> data = res.getData();
    System.out.println(data);

    for (LinkedHashMap<String,Object> item : data) {
        System.out.println(item.get("deptno")+" "+item.get("dname")+" "+item.get("loc"));
    }
}

你可能感兴趣的:(#,SpringBoot)