SpringBoot 利用RestTemplate http測(cè)試
SpringBoot RestTemplate http測(cè)試
spring-boot有關(guān)spring-boot測(cè)試的一些問(wèn)題
這測(cè)試的時(shí)候主程序沒(méi)有啟動(dòng)報(bào)錯(cuò)。錯(cuò)誤如下
==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(cè)試的類寫(xiě)了url 的問(wèn)題
具體的測(cè)試方法如下
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ù)沒(méi)有啟動(dòng)的原因,確實(shí),當(dāng)服務(wù)啟動(dòng)的時(shí)候,這個(gè)錯(cuò)誤就會(huì)沒(méi)有,這時(shí)候可以得出一個(gè)結(jié)論,就是Test的時(shí)候主函數(shù)是沒(méi)有啟動(dòng)。需要啟動(dòng)主函數(shù)參能測(cè)試,
但是有個(gè)問(wèn)題就是
當(dāng)測(cè)試時(shí)url不要http://localhost:39900沒(méi)有起動(dòng)主函數(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] 請(qǐng)求參數(shù)==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green
但是端口號(hào)不是配置中的那個(gè),還有就是每次端口號(hào)都會(huì)不一樣,真的很奇怪;根本不按照配置來(lái)的,我覺(jué)得就是它沒(méi)有都配置,但是默認(rèn)端口不是8080嗎,現(xiàn)在是每次都變,只是隨機(jī)的一個(gè)端口號(hào),從這一面又能看出,其實(shí)測(cè)試不用單獨(dú)啟動(dòng)主函數(shù)的,測(cè)試類會(huì)啟動(dòng),訪問(wèn)不了是因?yàn)?,端口?hào)不對(duì),但是至于怎么解決目前沒(méi)有想到. 但是也不影響開(kāi)發(fā),因?yàn)槲艺J(rèn)為服務(wù)端都沒(méi)啟動(dòng),客戶端怎么能訪問(wèn)呢。
至于測(cè)試會(huì)加載springbootApplication但是端口不一樣,沒(méi)有執(zhí)行加載端口類的結(jié)果。
SpringBoot RestTemplate測(cè)試Controller
1、功能測(cè)試類
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號(hào)", 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號(hào)", 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號(hào)", 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號(hào)", ProductStatus.AUDITING.getCode(), BigDecimal.valueOf(10), BigDecimal.valueOf(1), 7, BigDecimal.valueOf(3.42), "memo", new Date(), new Date(), "zemel", "zemel"); exceptions.add(e1); // 異常處理對(duì)象 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 請(qǐng)求 * * @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形式的請(qǐng)求頭 * * @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-請(qǐng)求參數(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-請(qǐng)求參數(shù):{}", formEntity.toString()); return formEntity; } /** * 生成Get請(qǐng)求內(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(); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot使用RestTemplate發(fā)送http請(qǐng)求的實(shí)操演示
- SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請(qǐng)求詳解
- springboot中RestTemplate發(fā)送HTTP請(qǐng)求的實(shí)現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對(duì)比分析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯?wèn)題
- SpringBoot使用RestTemplate如何通過(guò)http請(qǐng)求將文件下載到本地
相關(guān)文章
java基于netty NIO的簡(jiǎn)單聊天室的實(shí)現(xiàn)
這篇文章主要介紹了java基于netty NIO的簡(jiǎn)單聊天室的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Java連接SQL?Server數(shù)據(jù)庫(kù)的超詳細(xì)教程
在Java應(yīng)用程序中我們經(jīng)常需要與數(shù)據(jù)庫(kù)進(jìn)行交互,一種常見(jiàn)的數(shù)據(jù)庫(kù)是Microsoft?SQL?Server,下面這篇文章主要給大家介紹了關(guān)于Java連接SQL?Server數(shù)據(jù)庫(kù)的超詳細(xì)教程,需要的朋友可以參考下2024-01-01Java圖片與二進(jìn)制相互轉(zhuǎn)換實(shí)現(xiàn)示例講解
這篇文章主要介紹了Java圖片與二進(jìn)制相互轉(zhuǎn)換實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-03-03SpringBoot +Vue開(kāi)發(fā)考試系統(tǒng)的教程
這篇文章主要介紹了SpringBoot +Vue開(kāi)發(fā)考試系統(tǒng),支持多種題型:選擇題、多選題、判斷題、填空題、綜合題以及數(shù)學(xué)公式。支持在線考試,教師在線批改試卷。本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-05-05Java中g(shù)etResourceAsStream用法分析
這篇文章主要介紹了Java中g(shù)etResourceAsStream用法,較為詳細(xì)的分析了getResourceAsStream的功能及用法,需要的朋友可以參考下2015-06-06springboot配置文件屬性變量引用方式${}和@@用法及區(qū)別說(shuō)明
這篇文章主要介紹了springboot配置文件屬性變量引用方式${}和@@用法及區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot事務(wù)使用及回滾實(shí)現(xiàn)代碼詳解
這篇文章主要介紹了SpringBoot事務(wù)使用及回滾實(shí)現(xiàn)代碼詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08IntelliJ IDEA使用教程從入門(mén)到上癮(2019圖文版)
這篇文章主要介紹了IntelliJ IDEA使用教程從入門(mén)到上癮(2019圖文版),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12