spring-boot:TestRestTemplate、RestTemplate
RestTemplate
RestTemplate用于去调用远程的 REST services 时, Spring Boot 不会自动提供RestTemplate bean,但是会 auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed.
e.g.
1 |
|
controller
1 |
|
TestRestTemplate
测试用的RestTemplate,如果使用了@SpringBootTest,会自动配置一个TestRestTemplate,可直接使用。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.class) (SpringRunner
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoControllerTest {
private TestRestTemplate restTemplate;
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("howdy!");
}
public void getPathVariableTest() {
String body = this.restTemplate.getForObject("/v/this is a variable", String.class);
assertThat(body).isEqualTo("this is a variable");
}
public void postTest() {
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("date","2018-09-09");
map.add("variable","a post variable");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
String body = this.restTemplate.postForObject("/post",entity,String.class);
assertThat(body).isEqualTo("a post variable");
}
public void handleFileUpload() {
String path="C:/Users/dy040/Pictures/mm.jpg";
File file=new File(path);
FileSystemResource resource =new FileSystemResource(file);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<String, Object>();
map.add("file",resource);
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
String body = this.restTemplate.postForObject("/upload",map,String.class);
assertThat(body).isEqualTo("success");
}
static class Config {
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().setConnectTimeout(1000).setReadTimeout(1000);
}
}
}