Skip to content

Commit 9c6cfa3

Browse files
author
Dmitry Zinkevich
committed
[RestTemplate] Create unit tests for GET and POST methods
1 parent 7036c27 commit 9c6cfa3

File tree

5 files changed

+199
-2
lines changed

5 files changed

+199
-2
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package org.baeldung.persistence.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4+
5+
@JsonIgnoreProperties(ignoreUnknown = true)
6+
public class Owner {
7+
private String login;
8+
private String url;
9+
10+
public String getLogin() {
11+
return login;
12+
}
13+
14+
public void setLogin(String login) {
15+
this.login = login;
16+
}
17+
18+
public String getUrl() {
19+
return url;
20+
}
21+
22+
public void setUrl(String url) {
23+
this.url = url;
24+
}
25+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.persistence.model;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4+
5+
@JsonIgnoreProperties(ignoreUnknown = true)
6+
public class Repository {
7+
private long id;
8+
private String name;
9+
10+
private Owner owner;
11+
12+
public long getId() {
13+
return id;
14+
}
15+
16+
public void setId(long id) {
17+
this.id = id;
18+
}
19+
20+
public String getName() {
21+
return name;
22+
}
23+
24+
public void setName(String name) {
25+
this.name = name;
26+
}
27+
28+
public Owner getOwner() {
29+
return owner;
30+
}
31+
32+
public void setOwner(Owner owner) {
33+
this.owner = owner;
34+
}
35+
}

spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55

66
@StaticMetamodel(User.class)
77
public class User_ {
8+
public static volatile SingularAttribute<User, Long> id;
89
public static volatile SingularAttribute<User, String> firstName;
910
public static volatile SingularAttribute<User, String> lastName;
1011
public static volatile SingularAttribute<User, Integer> age;
12+
public static volatile SingularAttribute<User, String> email;
1113
}

spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,15 @@ public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestPar
8585

8686
@RequestMapping(method = RequestMethod.POST)
8787
@ResponseStatus(HttpStatus.CREATED)
88-
public void create(@RequestBody final Foo resource, final HttpServletResponse response) {
88+
@ResponseBody
89+
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
8990
Preconditions.checkNotNull(resource);
90-
final Long idOfCreatedResource = service.create(resource).getId();
91+
Foo foo = service.create(resource);
92+
final Long idOfCreatedResource = foo.getId();
9193

9294
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
95+
96+
return foo;
9397
}
9498

9599
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
package org.baeldung.client;
2+
3+
import com.fasterxml.jackson.databind.JsonNode;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import org.apache.http.auth.AuthScope;
6+
import org.apache.http.auth.UsernamePasswordCredentials;
7+
import org.apache.http.client.config.RequestConfig;
8+
import org.apache.http.impl.client.BasicCredentialsProvider;
9+
import org.apache.http.impl.client.CloseableHttpClient;
10+
import org.apache.http.impl.client.HttpClientBuilder;
11+
import org.baeldung.persistence.model.Foo;
12+
import org.baeldung.persistence.model.Repository;
13+
import org.baeldung.spring.PersistenceConfig;
14+
import org.junit.Before;
15+
import org.junit.Test;
16+
import org.junit.runner.RunWith;
17+
import org.springframework.http.HttpEntity;
18+
import org.springframework.http.HttpStatus;
19+
import org.springframework.http.ResponseEntity;
20+
import org.springframework.http.client.ClientHttpRequestFactory;
21+
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
22+
import org.springframework.http.converter.HttpMessageConverter;
23+
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
24+
import org.springframework.test.context.ContextConfiguration;
25+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
26+
import org.springframework.web.client.RestTemplate;
27+
28+
import java.io.IOException;
29+
import java.util.ArrayList;
30+
import java.util.List;
31+
32+
import static org.hamcrest.CoreMatchers.is;
33+
import static org.hamcrest.CoreMatchers.not;
34+
import static org.hamcrest.CoreMatchers.notNullValue;
35+
import static org.hamcrest.MatcherAssert.assertThat;
36+
37+
@RunWith(SpringJUnit4ClassRunner.class)
38+
@ContextConfiguration(classes = { PersistenceConfig.class })
39+
public class RestTemplateLiveTest {
40+
41+
RestTemplate restTemplate;
42+
private List<HttpMessageConverter<?>> messageConverters;
43+
private final String userReposUrl = "https://api.github.com/users/eugenp/repos";
44+
private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials";
45+
46+
@Before
47+
public void beforeTest() {
48+
restTemplate = new RestTemplate();
49+
50+
messageConverters = new ArrayList<>();
51+
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
52+
jsonMessageConverter.setObjectMapper(new ObjectMapper());
53+
messageConverters.add(jsonMessageConverter);
54+
}
55+
56+
@Test
57+
public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
58+
ResponseEntity<String> response = restTemplate.getForEntity(userReposUrl, String.class);
59+
assertThat(response.getStatusCode(), is(HttpStatus.OK));
60+
}
61+
62+
@Test
63+
public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectRepoJson() throws IOException {
64+
ResponseEntity<String> response = restTemplate.getForEntity(repoUrl, String.class);
65+
66+
ObjectMapper mapper = new ObjectMapper();
67+
JsonNode root = mapper.readTree(response.getBody());
68+
69+
JsonNode name = root.path("name");
70+
assertThat(name.asText(), is("tutorials"));
71+
72+
JsonNode owner = root.path("owner").path("login");
73+
assertThat(owner.asText(), is("eugenp"));
74+
}
75+
76+
@Test
77+
public void givenRepoEndpoint_whenSendGetForObject_thenReturnsRepoObject() {
78+
restTemplate.setMessageConverters(messageConverters);
79+
String repoUrl = "https://api.github.com/repos/eugenp/tutorials";
80+
Repository repository = restTemplate.getForObject(repoUrl, Repository.class);
81+
82+
assertThat(repository.getName(), is("tutorials"));
83+
assertThat(repository.getOwner().getLogin(), is("eugenp"));
84+
}
85+
86+
@Test
87+
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
88+
String fooService = "http://localhost:8080/spring-security-rest-full/foos";
89+
90+
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
91+
RestTemplate restTemplate = new RestTemplate(requestFactory);
92+
93+
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
94+
Foo foo = restTemplate.postForObject(fooService, request, Foo.class);
95+
assertThat(foo, notNullValue());
96+
assertThat(foo.getName(), is("bar"));
97+
}
98+
99+
@Test
100+
public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() {
101+
String fooService = "http://localhost:8080/spring-security-rest-full/foos";
102+
103+
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
104+
RestTemplate restTemplate = new RestTemplate(requestFactory);
105+
106+
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
107+
Foo firstInstance = restTemplate.postForObject(fooService, request, Foo.class);
108+
Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class);
109+
assertThat(firstInstance, notNullValue());
110+
assertThat(secondInstance, notNullValue());
111+
assertThat(firstInstance, not(secondInstance));
112+
}
113+
114+
private ClientHttpRequestFactory getClientHttpRequestFactory() {
115+
int timeout = 5;
116+
RequestConfig config = RequestConfig.custom()
117+
.setConnectTimeout(timeout * 1000)
118+
.setConnectionRequestTimeout(timeout * 1000)
119+
.setSocketTimeout(timeout * 1000).build();
120+
121+
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
122+
credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM),
123+
new UsernamePasswordCredentials("user1", "user1Pass"));
124+
125+
CloseableHttpClient client = HttpClientBuilder.create()
126+
.setDefaultRequestConfig(config)
127+
.setDefaultCredentialsProvider(credentialsProvider).build();
128+
129+
return new HttpComponentsClientHttpRequestFactory(client);
130+
}
131+
}

0 commit comments

Comments
 (0)