Skip to content

Commit 7dc0baf

Browse files
author
Dmitry Zinkevich
committed
[RestTemplate] Create unit tests for exchange() and execute() methods
1 parent 7f78499 commit 7dc0baf

File tree

1 file changed

+92
-8
lines changed

1 file changed

+92
-8
lines changed

spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java

Lines changed: 92 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.fasterxml.jackson.databind.JsonNode;
44
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import com.google.common.base.Charsets;
56
import org.apache.http.auth.AuthScope;
67
import org.apache.http.auth.UsernamePasswordCredentials;
78
import org.apache.http.client.config.RequestConfig;
@@ -14,26 +15,26 @@
1415
import org.junit.Before;
1516
import org.junit.Test;
1617
import org.junit.runner.RunWith;
17-
import org.springframework.http.HttpEntity;
18-
import org.springframework.http.HttpStatus;
19-
import org.springframework.http.ResponseEntity;
18+
import org.springframework.http.*;
2019
import org.springframework.http.client.ClientHttpRequestFactory;
2120
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
2221
import org.springframework.http.converter.HttpMessageConverter;
2322
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
2423
import org.springframework.test.context.ContextConfiguration;
2524
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
25+
import org.springframework.web.client.RequestCallback;
2626
import org.springframework.web.client.RestTemplate;
2727

2828
import java.io.IOException;
29-
import java.util.ArrayList;
30-
import java.util.List;
29+
import java.util.*;
3130

31+
import static org.apache.commons.codec.binary.Base64.encodeBase64;
3232
import static org.hamcrest.CoreMatchers.is;
3333
import static org.hamcrest.CoreMatchers.not;
34-
import static org.hamcrest.CoreMatchers.notNullValue;
3534
import static org.hamcrest.MatcherAssert.assertThat;
36-
35+
import static org.hamcrest.Matchers.contains;
36+
import static org.hamcrest.Matchers.notNullValue;
37+
import static org.junit.Assert.assertTrue;
3738
@RunWith(SpringJUnit4ClassRunner.class)
3839
@ContextConfiguration(classes = { PersistenceConfig.class })
3940
public class RestTemplateLiveTest {
@@ -42,6 +43,7 @@ public class RestTemplateLiveTest {
4243
private List<HttpMessageConverter<?>> messageConverters;
4344
private final String userReposUrl = "https://api.github.com/users/eugenp/repos";
4445
private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials";
46+
private final String fooService = "http://localhost:8080/spring-security-rest-full/foos";
4547

4648
@Before
4749
public void beforeTest() {
@@ -108,7 +110,7 @@ public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime()
108110
Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class);
109111
assertThat(firstInstance, notNullValue());
110112
assertThat(secondInstance, notNullValue());
111-
assertThat(firstInstance, not(secondInstance));
113+
assertThat(firstInstance.getId(), not(secondInstance.getId()));
112114
}
113115

114116
private ClientHttpRequestFactory getClientHttpRequestFactory() {
@@ -128,4 +130,86 @@ private ClientHttpRequestFactory getClientHttpRequestFactory() {
128130

129131
return new HttpComponentsClientHttpRequestFactory(client);
130132
}
133+
134+
@Test
135+
public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
136+
String repoUrl = "https://api.github.com/repos/eugenp/{repoName}";
137+
RestTemplate template = new RestTemplate();
138+
139+
Map<String, Object> uriVariables = new HashMap<>();
140+
uriVariables.put("repoName", "tutorials");
141+
142+
HttpHeaders httpHeaders = template.headForHeaders(repoUrl, uriVariables);
143+
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
144+
assertThat(httpHeaders.get("X-RateLimit-Limit"), contains("60"));
145+
}
146+
147+
@Test
148+
public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
149+
RestTemplate template = new RestTemplate(getClientHttpRequestFactory());
150+
Set<HttpMethod> optionsForAllow = template.optionsForAllow(fooService);
151+
HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE};
152+
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
153+
}
154+
155+
@Test
156+
public void givenRestService_whenPostResource_thenResourceIsCreated() {
157+
RestTemplate restTemplate = new RestTemplate();
158+
159+
HttpHeaders headers = prepareBasicAuthHeaders();
160+
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
161+
162+
ResponseEntity<Foo> response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class);
163+
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
164+
Foo foo = response.getBody();
165+
assertThat(foo, notNullValue());
166+
assertThat(foo.getName(), is("bar"));
167+
assertThat(foo.getId(), is(1L));
168+
}
169+
170+
private HttpHeaders prepareBasicAuthHeaders() {
171+
HttpHeaders headers = new HttpHeaders();
172+
String encodedLogPass = getBase64EncodedLogPass();
173+
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
174+
return headers;
175+
}
176+
177+
private String getBase64EncodedLogPass() {
178+
String logPass = "user1:user1Pass";
179+
byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
180+
return new String(authHeaderBytes, Charsets.US_ASCII);
181+
}
182+
183+
@Test
184+
public void givenResource_whenPutExistingEntity_thenItIsUpdated() {
185+
RestTemplate restTemplate = new RestTemplate();
186+
HttpHeaders headers = prepareBasicAuthHeaders();
187+
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
188+
189+
//Create entity
190+
ResponseEntity<Foo> response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class);
191+
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
192+
assertThat(response.getBody().getId(), is(1L));
193+
194+
//Update entity
195+
Foo updatedInstance = new Foo("newName");
196+
updatedInstance.setId(1);
197+
String resourceUrl = fooService + "/1";
198+
restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
199+
200+
//Check that entity was updated
201+
response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
202+
Foo foo = response.getBody();
203+
assertThat(foo.getId(), is(1L));
204+
assertThat(foo.getName(), is(updatedInstance.getName()));
205+
}
206+
207+
private RequestCallback requestCallback(Foo updatedInstace) {
208+
return clientHttpRequest -> {
209+
ObjectMapper mapper = new ObjectMapper();
210+
mapper.writeValue(clientHttpRequest.getBody(), updatedInstace);
211+
clientHttpRequest.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
212+
clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
213+
};
214+
}
131215
}

0 commit comments

Comments
 (0)