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è)試的類(lèi)寫(xiě)了url 的問(wèn)題
具體的測(cè)試方法如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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ù)如下
1
2
3
4
5
6
7
8
|
@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è)試類(lèi)會(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í)行加載端口類(lèi)的結(jié)果。
SpringBoot RestTemplate測(cè)試Controller
1、功能測(cè)試類(lèi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
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、工具類(lèi)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
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è)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/AdesKng/article/details/80204521