SpringBoot 利用RestTemplate http測試
SpringBoot RestTemplate http測試
spring-boot有關(guān)spring-boot測試的一些問題
這測試的時(shí)候主程序沒有啟動(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試的類寫了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ù)沒有啟動(dòng)的原因,確實(shí),當(dāng)服務(wù)啟動(dòng)的時(shí)候,這個(gè)錯(cuò)誤就會(huì)沒有,這時(shí)候可以得出一個(gè)結(jié)論,就是Test的時(shí)候主函數(shù)是沒有啟動(dòng)。需要啟動(dòng)主函數(shù)參能測試,
但是有個(gè)問題就是
當(dāng)測試時(shí)url不要http://localhost:39900沒有起動(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] 請求參數(shù)==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green
但是端口號(hào)不是配置中的那個(gè),還有就是每次端口號(hào)都會(huì)不一樣,真的很奇怪;根本不按照配置來的,我覺得就是它沒有都配置,但是默認(rèn)端口不是8080嗎,現(xiàn)在是每次都變,只是隨機(jī)的一個(gè)端口號(hào),從這一面又能看出,其實(shí)測試不用單獨(dú)啟動(dòng)主函數(shù)的,測試類會(huì)啟動(dòng),訪問不了是因?yàn)?,端口?hào)不對,但是至于怎么解決目前沒有想到. 但是也不影響開發(fā),因?yàn)槲艺J(rèn)為服務(wù)端都沒啟動(dòng),客戶端怎么能訪問呢。
至于測試會(huì)加載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號(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);
// 異常處理對象
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();
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot使用RestTemplate發(fā)送http請求的實(shí)操演示
- SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請求詳解
- springboot中RestTemplate發(fā)送HTTP請求的實(shí)現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對比分析
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- SpringBoot使用RestTemplate如何通過http請求將文件下載到本地
相關(guān)文章
Struts1教程之ActionMapping_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Struts1教程之ActionMapping,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
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
MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟
這篇文章主要介紹了MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02
關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy
這篇文章主要介紹了關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

