最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot 利用RestTemplate http測試

 更新時間:2021年08月19日 11:24:10   作者:AdesKng  
這篇文章主要介紹了SpringBoot 利用RestTemplate http測試,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

SpringBoot RestTemplate http測試

spring-boot有關(guān)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)==

這是因?yàn)闇y試的類寫了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"));
    }
}

主函數(shù)如下

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

這樣可以認(rèn)為是服務(wù)沒有啟動的原因,確實(shí),當(dāng)服務(wù)啟動的時候,這個錯誤就會沒有,這時候可以得出一個結(jié)論,就是Test的時候主函數(shù)是沒有啟動。需要啟動主函數(shù)參能測試,

但是有個問題就是

當(dāng)測試時url不要http://localhost:39900沒有起動主函數(shù)一樣能成功

[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] 請求參數(shù)==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green

但是端口號不是配置中的那個,還有就是每次端口號都會不一樣,真的很奇怪;根本不按照配置來的,我覺得就是它沒有都配置,但是默認(rèn)端口不是8080嗎,現(xiàn)在是每次都變,只是隨機(jī)的一個端口號,從這一面又能看出,其實(shí)測試不用單獨(dú)啟動主函數(shù)的,測試類會啟動,訪問不了是因?yàn)?,端口號不對,但是至于怎么解決目前沒有想到. 但是也不影響開發(fā),因?yàn)槲艺J(rèn)為服務(wù)端都沒啟動,客戶端怎么能訪問呢。

至于測試會加載springbootApplication但是端口不一樣,沒有執(zhí)行加載端口類的結(jié)果。

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執(zhí)行順序
public class ProductControllerTest { 
// @Autowired
// private TestRestTemplate rest; 
 private static RestTemplate rest = new RestTemplate(); 
 @Value("http://localhost:${local.server.port}/products")
 private String baseUrl; 
 // 正常數(shù)據(jù)
 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); 
    /**
     * 發(fā)送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 響應(yīng)信息:{}", 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-請求參數(shù):{}", 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-請求參數(shù):{}", formEntity.toString());
        return formEntity;
    }  
    /**
     * 生成Get請求內(nèi)容
     *
     * @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();
    }
}

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Arrays.asList方法總結(jié)

    Arrays.asList方法總結(jié)

    本文主要對Arrays.asList方法進(jìn)行總結(jié)。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • Struts1教程之ActionMapping_動力節(jié)點(diǎn)Java學(xué)院整理

    Struts1教程之ActionMapping_動力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要介紹了Struts1教程之ActionMapping,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Java輕松掌握面向?qū)ο蟮娜筇匦苑庋b與繼承和多態(tài)

    Java輕松掌握面向?qū)ο蟮娜筇匦苑庋b與繼承和多態(tài)

    本文主要講述的是面向?qū)ο蟮娜筇匦裕悍庋b,繼承,多態(tài),內(nèi)容含括從封裝到繼承再到多態(tài)的所有重點(diǎn)內(nèi)容以及使用細(xì)節(jié)和注意事項(xiàng),內(nèi)容有點(diǎn)長,請大家耐心看完
    2022-05-05
  • SpringBoot?Starter的工作原理解析

    SpringBoot?Starter的工作原理解析

    SpringBootStarter是SpringBoot項(xiàng)目中用于簡化配置的工具,通過自動配置和條件加載機(jī)制,它自動生成所需的組件和服務(wù),減少了開發(fā)時間和配置工作,本文介紹SpringBoot?Starter的工作原理,感興趣的朋友一起看看吧
    2025-02-02
  • MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟

    MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟

    這篇文章主要介紹了MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • Java詳解線上內(nèi)存暴漲問題定位和解決方案

    Java詳解線上內(nèi)存暴漲問題定位和解決方案

    本篇文章介紹了我在開發(fā)過程中遇到的線上內(nèi)存暴漲的問題,以及定位問題原因和解決該問題的過程及思路,通讀本篇對大家的學(xué)習(xí)或工作具有一定的價值,需要的朋友可以參考下
    2021-10-10
  • 深入了解Java File分隔符和Path分隔符的使用

    深入了解Java File分隔符和Path分隔符的使用

    不同的操作系統(tǒng)使用不同的字符作為文件和路徑分隔符。當(dāng)我們的應(yīng)用程序需要在多個平臺上運(yùn)行時,我們需要正確處理這些問題。Java幫助我們選擇一個合適的分隔符,本文就來聊聊Java中File分隔符和 Path分隔符的使用
    2022-07-07
  • java實(shí)現(xiàn)圖片壓縮的思路與代碼

    java實(shí)現(xiàn)圖片壓縮的思路與代碼

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖片壓縮的思路與代碼,將較大的圖片按照指定的寬高,以寬為基準(zhǔn),或高為基準(zhǔn)按照等比例壓縮圖片,感興趣的小伙伴們可以參考一下
    2016-03-03
  • 關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy

    關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy

    這篇文章主要介紹了關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • MyBatis一二級緩存

    MyBatis一二級緩存

    這篇文章主要介紹了MyBatis一二級緩存的相關(guān)知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-06-06

最新評論

深水埗区| 壤塘县| 黄龙县| 永济市| 右玉县| 赤城县| 铁力市| 米易县| 松原市| 巧家县| 乌苏市| 莆田市| 贺州市| 克什克腾旗| 仪陇县| 铜川市| 滦平县| 乡城县| 修武县| 庄河市| 原平市| 左贡县| 个旧市| 潮安县| 共和县| 永吉县| 朔州市| 延长县| 克东县| 麻江县| 安庆市| 沾益县| 长子县| 竹溪县| 尼玛县| 新沂市| 中山市| 扎囊县| 宁河县| 常山县| 齐河县|