SpringBoot-RestTemplate测试Controller

1、功能测试类

package com.imooc.controller;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
 
import com.imooc.entity.Product;
import com.imooc.entity.enums.ProductStatus;
import com.imooc.util.RestUtil;
 
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING) // case执行顺序
public class ProductControllerTest {
 
//    @Autowired
//    private TestRestTemplate rest;
    
    private static RestTemplate rest = new RestTemplate();
    
    @Value("http://localhost:${local.server.port}/products")
    private String baseUrl;
    
    // 正常数据
    private static List<Product> normals = new ArrayList<>();
    
    private static List<Product> exceptions = new ArrayList<>();
    
    @Before
    public void init(){
        
        Product p1 = new Product("T0001", "零活宝1号", ProductStatus.AUDITING.getCode(),
                BigDecimal.valueOf(10), BigDecimal.valueOf(1), 7, 
                BigDecimal.valueOf(3.42), "memo", new Date(), new Date(), "zemel", "zemel");
        Product p2 = new Product("T0002", "零活宝2号", ProductStatus.AUDITING.getCode(),
                BigDecimal.valueOf(10), BigDecimal.valueOf(0), 6, 
                BigDecimal.valueOf(3.42), "memo", new Date(), new Date(), "zemel", "zemel");
        Product p3 = new Product("T0003", "零活宝3号", ProductStatus.AUDITING.getCode(),
                BigDecimal.valueOf(100), BigDecimal.valueOf(10),3, 
                BigDecimal.valueOf(3.42), "memo", new Date(), new Date(), "zemel", "zemel");
        normals.add(p1);
        normals.add(p2);
        normals.add(p3);
        
        Product e1 = new Product(null, "零活宝1号", ProductStatus.AUDITING.getCode(),
                BigDecimal.valueOf(10), BigDecimal.valueOf(1), 7, 
                BigDecimal.valueOf(3.42), "memo", new Date(), new Date(), "zemel", "zemel");
        exceptions.add(e1);
        
        // 异常处理对象
        ResponseErrorHandler errorHandler = new ResponseErrorHandler() {
            
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                
                return true;
            }
            
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                // TODO Auto-generated method stub
                
            }
        };
        rest.setErrorHandler(errorHandler);
    }
    
    @Test
    public void testAddProduct() {
        normals.forEach(product -> {
            Product result = RestUtil.postJSON(rest, baseUrl, product, Product.class);
            Assert.notNull(result.getCreateAt(), "插入失败");
        });
    }
    
    @Test
    public void testAddProductException() {
        exceptions.forEach(product -> {
            Map<String, String> result = RestUtil.postJSON(rest, baseUrl, product, HashMap.class);
//            Assert.notNull(result.getCreateAt(), "插入失败");
            System.out.println(result);
            Assert.notNull(result.get("message").equals(product.getName()), "插入成功");
        });
    }
    
 
    @Test
    public void testFindOne() {
        normals.forEach(p->{
            
            Product result = rest.getForObject(baseUrl+"/"+p.getId(), Product.class);
            Assert.isTrue(result.getId().equals(p.getId()));
        });
        
        exceptions.forEach(p->{
            Product result = rest.getForObject(baseUrl+"/"+p.getId(), Product.class);
            Assert.isNull(result, "查询失败");
        
            
        });
    }
    
    @Test
    public void testQuery() {
        
//        Page<Product> page = rest.getForObject(baseUrl, "", Page.class);
        
        Map<String, Object> params = new HashMap<>();
        params.put("ids", "T0001,T0002");
//        Page<Product> page = RestUtil.postJSON(rest, baseUrl, params, Page.class);
        
        Map page = rest.getForObject(baseUrl, HashMap.class, params);
        System.out.println(page);
        System.out.println(page.get("pageable"));
        System.out.println(page.get("content"));
        Assert.notNull(page);
    }
 
}

2、工具类

package com.imooc.util;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
 
import java.util.Arrays;
import java.util.List;
import java.util.Map;
 
 
public class RestUtil {
 
    static Logger log = LoggerFactory.getLogger(RestUtil.class);
 
    /**
     * 发送post 请求
     *
     * @param restTemplate
     * @param url
     * @param param
     * @param responseType
     * @param <T>
     * @return
     */
    public static <T> T postJSON(RestTemplate restTemplate, String url, Object param, Class<T> responseType) {
        HttpEntity<String> formEntity = makePostJSONEntiry(param);
        T result = restTemplate.postForObject(url, formEntity, responseType);
        log.info("rest-post-json 响应信息:{}", JsonUtil.toJson(result));
        return result;
    }
 
    /**
     * 生成json形式的请求头
     *
     * @param param
     * @return
     */
    public static HttpEntity<String> makePostJSONEntiry(Object param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<String> formEntity = new HttpEntity<String>(
                JsonUtil.toJson(param), headers);
        log.info("rest-post-json-请求参数:{}", formEntity.toString());
        return formEntity;
    }
 
 
    public static HttpEntity<String> makePostTextEntiry(Map<String, ? extends Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<String> formEntity = new HttpEntity<String>(
                makeGetParamContent(param), headers);
        log.info("rest-post-text-请求参数:{}", formEntity.toString());
        return formEntity;
    }
 
 
    /**
     * 生成Get请求内容
     *
     * @param param
     * @param excluedes
     * @return
     */
    public static String makeGetParamContent(Map<String, ? extends Object> param, String... excluedes) {
        StringBuilder content = new StringBuilder();
        List<String> excludeKeys = Arrays.asList(excluedes);
        param.forEach((key, v) -> {
            content.append(key).append("=").append(v).append("&");
        });
        if (content.length() > 0) {
            content.deleteCharAt(content.length() - 1);
        }
        return content.toString();
    }
}

Json对象转换成Josn数组

原文地址:https://www.cnblogs.com/edda/p/14592646.html