java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot RestTemplate http测试

SpringBoot 利用RestTemplate http测试

作者:AdesKng

这篇文章主要介绍了SpringBoot 利用RestTemplate http测试,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringBoot RestTemplate http测试

spring-boot有关spring-boot测试的一些问题

这测试的时候主程序没有启动报错。错误如下

==org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:39900/migrate/test": Connect to localhost:39900 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:39900 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)==

这是因为测试的类写了url 的问题

具体的测试方法如下

package api;
import com.hera.WebApplication;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class Test {
    @Autowired
    public TestRestTemplate restTemplate;
    @org.junit.Test
    public void home(){
        String url="http://localhost:39900/migrate/test";
      Map map=restTemplate.getForObject(url,Map.class);
        System.out.println(map.get("red"));
    }
}

主函数如下

@ComponentScan(basePackages={"com.hera"})
@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = ExtJpaRepositoryFactoryBean.class)
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

这样可以认为是服务没有启动的原因,确实,当服务启动的时候,这个错误就会没有,这时候可以得出一个结论,就是Test的时候主函数是没有启动。需要启动主函数参能测试,

但是有个问题就是

当测试时url不要http://localhost:39900没有起动主函数一样能成功

[INFO][2018-04-29T22:40:02.455+0800][BusinessHandlerInterceptor.java:28] 【LOG HANDLER】 url=http://localhost:63857/migrate/test, traceId=null
..............................
[INFO][2018-04-29T22:40:02.976+0800][BusinessHandlerInterceptor.java:48] 请求参数==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green

但是端口号不是配置中的那个,还有就是每次端口号都会不一样,真的很奇怪;根本不按照配置来的,我觉得就是它没有都配置,但是默认端口不是8080吗,现在是每次都变,只是随机的一个端口号,从这一面又能看出,其实测试不用单独启动主函数的,测试类会启动,访问不了是因为,端口号不对,但是至于怎么解决目前没有想到. 但是也不影响开发,因为我认为服务端都没启动,客户端怎么能访问呢。

至于测试会加载springbootApplication但是端口不一样,没有执行加载端口类的结果。

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();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文