SpringBoot TestRestTemplate

发布于:2024-05-15 ⋅ 阅读:(140) ⋅ 点赞:(0)

1 什么是 TestRestTemplate ?

Spring Boot 的 TestRestTemplate 是用于在集成测试中测试 RESTful 服务的工具类。它提供了一种方便的方式来发送 HTTP 请求并验证响应。TestRestTemplate 可以模拟客户端的行为,与实际的 REST 客户端类似,但适用于集成测试环境。

2 为什么使用 TestRestTemplate?

方便:TestRestTemplate 提供了一种方便的方式来发送 HTTP 请求和验证响应,而无需手动创建和配置 HTTP 客户端。
集成度高:它能够模拟客户端的行为,包括发送各种类型的请求(GET、POST、PUT、DELETE 等)和处理响应。
适用于集成测试:TestRestTemplate 是专门为集成测试设计的,它与 Spring Boot 集成良好,并且支持自动配置。

3 如何使用 TestRestTemplate?

要在测试中使用 TestRestTemplate,你首先需要创建一个 TestRestTemplate 实例,并使用它来构建和执行 HTTP 请求,然后验证响应。

3.1 Controller

package com.xu.test.controller;

import com.xu.test.service.TestService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private TestService testService;


    @RequestMapping("/test1")
    public String test1(String a, Integer b) {
        return testService.test1(a, b);
    }

    @RequestMapping("/test2")
    public Object test2(HttpServletRequest request, HttpServletResponse response, String a, Integer b) {
        testService.test2(request, response, a, b);
        Map<String, Object> body = new HashMap<>();
        body.put("a", a);
        body.put("b", b);
        return body;
    }

}

3.2 测试代码

package com.xu.test;

import com.xu.test.service.TestService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class) // 声明使用 SpringRunner 进行测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // 声明使用随机端口启动 Spring Boot 应用程序
public class MockMvcTest4 {

    private String token = "1111";

    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private TestService testService;

    @Test
    public void post() {
        String json = "{\n" +
                "    \"type\": 1,\n" +
                "    \"procInsId\": \"2330001\"" +
                "}";
        // 创建HTTP头部
        HttpHeaders head = new HttpHeaders();
        head.set("X-Access-Token", token);
        head.setContentType(MediaType.APPLICATION_JSON);
        // 创建HTTP实体,封装请求体和头部信息
        HttpEntity<String> body = new HttpEntity<>(json, head);
        // 使用TestRestTemplate发送POST请求
        ResponseEntity<?> response = restTemplate.postForEntity("/test/test2", body,
                String.class);
        // 断言
        Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
    }


    @Test
    public void get() throws Exception {
        // 创建HTTP头部
        HttpHeaders head = new HttpHeaders();
        head.set("X-Access-Token", token);
        head.setContentType(MediaType.APPLICATION_JSON);
        // 使用TestRestTemplate发送POST请求
        ResponseEntity<?> response = restTemplate.getForEntity("/test/test1?a=1&b=2", String.class);
        // 断言
        Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
    }

}