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)==
這是因為測試的類寫了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); } }
這樣可以認為是服務(wù)沒有啟動的原因,確實,當服務(wù)啟動的時候,這個錯誤就會沒有,這時候可以得出一個結(jié)論,就是Test的時候主函數(shù)是沒有啟動。需要啟動主函數(shù)參能測試,
但是有個問題就是
當測試時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
但是端口號不是配置中的那個,還有就是每次端口號都會不一樣,真的很奇怪;根本不按照配置來的,我覺得就是它沒有都配置,但是默認端口不是8080嗎,現(xiàn)在是每次都變,只是隨機的一個端口號,從這一面又能看出,其實測試不用單獨啟動主函數(shù)的,測試類會啟動,訪問不了是因為,端口號不對,但是至于怎么解決目前沒有想到. 但是也不影響開發(fā),因為我認為服務(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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- SpringBoot使用RestTemplate發(fā)送http請求的實操演示
- SpringBoot使用RestTemplate實現(xiàn)HTTP請求詳解
- springboot中RestTemplate發(fā)送HTTP請求的實現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對比分析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- SpringBoot使用RestTemplate如何通過http請求將文件下載到本地
相關(guān)文章
java基于netty NIO的簡單聊天室的實現(xiàn)
這篇文章主要介紹了java基于netty NIO的簡單聊天室的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2020-07-07Java連接SQL?Server數(shù)據(jù)庫的超詳細教程
在Java應(yīng)用程序中我們經(jīng)常需要與數(shù)據(jù)庫進行交互,一種常見的數(shù)據(jù)庫是Microsoft?SQL?Server,下面這篇文章主要給大家介紹了關(guān)于Java連接SQL?Server數(shù)據(jù)庫的超詳細教程,需要的朋友可以參考下2024-01-01Java圖片與二進制相互轉(zhuǎn)換實現(xiàn)示例講解
這篇文章主要介紹了Java圖片與二進制相互轉(zhuǎn)換實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習吧2023-03-03SpringBoot +Vue開發(fā)考試系統(tǒng)的教程
這篇文章主要介紹了SpringBoot +Vue開發(fā)考試系統(tǒng),支持多種題型:選擇題、多選題、判斷題、填空題、綜合題以及數(shù)學(xué)公式。支持在線考試,教師在線批改試卷。本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2020-05-05Java中g(shù)etResourceAsStream用法分析
這篇文章主要介紹了Java中g(shù)etResourceAsStream用法,較為詳細的分析了getResourceAsStream的功能及用法,需要的朋友可以參考下2015-06-06springboot配置文件屬性變量引用方式${}和@@用法及區(qū)別說明
這篇文章主要介紹了springboot配置文件屬性變量引用方式${}和@@用法及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot事務(wù)使用及回滾實現(xiàn)代碼詳解
這篇文章主要介紹了SpringBoot事務(wù)使用及回滾實現(xiàn)代碼詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2020-08-08IntelliJ IDEA使用教程從入門到上癮(2019圖文版)
這篇文章主要介紹了IntelliJ IDEA使用教程從入門到上癮(2019圖文版),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12