Merge pull request #245 from zinch84/rest_template_tutorial

[RestTemplate] Create unit test for delete() method
This commit is contained in:
Eugen 2015-09-11 07:06:19 -07:00
commit 08dd4e8ca9
4 changed files with 110 additions and 161 deletions

View File

@ -1,25 +0,0 @@
package org.baeldung.persistence.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Owner {
private String login;
private String url;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

View File

@ -1,35 +0,0 @@
package org.baeldung.persistence.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Repository {
private long id;
private String name;
private Owner owner;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}

View File

@ -1,9 +1,6 @@
package org.baeldung.web.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.google.common.base.Preconditions;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.web.exception.MyResourceNotFoundException;
@ -15,17 +12,13 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Controller
@RequestMapping(value = "/foos")
@ -110,4 +103,11 @@ public class FooController {
service.deleteById(id);
}
@RequestMapping(method = RequestMethod.HEAD)
@ResponseStatus(HttpStatus.OK)
public void head(HttpServletResponse resp) {
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
resp.setHeader("bar", "baz");
}
}

View File

@ -10,11 +10,12 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.baeldung.persistence.model.Foo;
import org.baeldung.persistence.model.Repository;
import org.baeldung.persistence.service.IFooService;
import org.baeldung.spring.PersistenceConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
@ -22,97 +23,165 @@ import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class })
@ContextConfiguration(classes = {PersistenceConfig.class})
public class RestTemplateLiveTest {
RestTemplate restTemplate;
private List<HttpMessageConverter<?>> messageConverters;
private final String userReposUrl = "https://api.github.com/users/eugenp/repos";
private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials";
private final String fooService = "http://localhost:8080/spring-security-rest-full/foos";
private static final String fooResourceUrl = "http://localhost:8080/spring-security-rest-full/foos";
@Autowired
private IFooService fooService;
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
restTemplate = new RestTemplate(getClientHttpRequestFactory());
messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
jsonMessageConverter.setObjectMapper(new ObjectMapper());
messageConverters.add(jsonMessageConverter);
ensureOneEntityExists();
}
@Test
public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(userReposUrl, String.class);
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), is(HttpStatus.OK));
}
@Test
public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectRepoJson() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(repoUrl, String.class);
public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectJson() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode name = root.path("name");
assertThat(name.asText(), is("tutorials"));
assertThat(name.asText(), is("bar"));
JsonNode owner = root.path("owner").path("login");
assertThat(owner.asText(), is("eugenp"));
JsonNode owner = root.path("id");
assertThat(owner.asText(), is("1"));
}
@Test
public void givenRepoEndpoint_whenSendGetForObject_thenReturnsRepoObject() {
restTemplate.setMessageConverters(messageConverters);
String repoUrl = "https://api.github.com/repos/eugenp/tutorials";
Repository repository = restTemplate.getForObject(repoUrl, Repository.class);
assertThat(repository.getName(), is("tutorials"));
assertThat(repository.getOwner().getLogin(), is("eugenp"));
Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
assertThat(foo.getName(), is("bar"));
assertThat(foo.getId(), is(1L));
}
@Test
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
String fooService = "http://localhost:8080/spring-security-rest-full/foos";
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooService, request, Foo.class);
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
}
@Test
public void givenFooService_whenPostFor2Objects_thenNewObjectIsCreatedEachTime() {
String fooService = "http://localhost:8080/spring-security-rest-full/foos";
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo firstInstance = restTemplate.postForObject(fooService, request, Foo.class);
Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class);
Foo firstInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
Foo secondInstance = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(firstInstance, notNullValue());
assertThat(secondInstance, notNullValue());
assertThat(firstInstance.getId(), not(secondInstance.getId()));
}
@Test
public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
assertTrue(httpHeaders.get("foo").contains("bar"));
}
@Test
public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE};
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
@Test
public void givenRestService_whenPostResource_thenResourceIsCreated() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = prepareBasicAuthHeaders();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Foo foo = response.getBody();
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
}
@Test
public void givenResource_whenPutExistingEntity_thenItIsUpdated() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = prepareBasicAuthHeaders();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
//Create entity
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
//Update entity
Foo updatedInstance = new Foo("newName");
updatedInstance.setId(response.getBody().getId());
String resourceUrl = fooResourceUrl + '/' + response.getBody().getId();
restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
//Check that entity was updated
response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
Foo foo = response.getBody();
assertThat(foo.getName(), is(updatedInstance.getName()));
}
@Test
public void givenRestService_whenCallDelete_thenEntityIsRemoved() {
String entityUrl = fooResourceUrl + "/1";
restTemplate.delete(entityUrl);
try {
restTemplate.getForEntity(entityUrl, Foo.class);
fail();
} catch (HttpClientErrorException ex) {
assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND));
}
}
private void ensureOneEntityExists() {
Foo instance = new Foo("bar");
if (fooService.findOne(1L) == null) {
fooService.create(instance);
}
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 5;
RequestConfig config = RequestConfig.custom()
@ -131,42 +200,6 @@ public class RestTemplateLiveTest {
return new HttpComponentsClientHttpRequestFactory(client);
}
@Test
public void givenResource_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
String repoUrl = "https://api.github.com/repos/eugenp/{repoName}";
RestTemplate template = new RestTemplate();
Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("repoName", "tutorials");
HttpHeaders httpHeaders = template.headForHeaders(repoUrl, uriVariables);
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
assertThat(httpHeaders.get("X-RateLimit-Limit"), contains("60"));
}
@Test
public void givenResource_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
RestTemplate template = new RestTemplate(getClientHttpRequestFactory());
Set<HttpMethod> optionsForAllow = template.optionsForAllow(fooService);
HttpMethod[] supportedMethods = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE};
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
@Test
public void givenRestService_whenPostResource_thenResourceIsCreated() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = prepareBasicAuthHeaders();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
ResponseEntity<Foo> response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Foo foo = response.getBody();
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
assertThat(foo.getId(), is(1L));
}
private HttpHeaders prepareBasicAuthHeaders() {
HttpHeaders headers = new HttpHeaders();
String encodedLogPass = getBase64EncodedLogPass();
@ -180,30 +213,6 @@ public class RestTemplateLiveTest {
return new String(authHeaderBytes, Charsets.US_ASCII);
}
@Test
public void givenResource_whenPutExistingEntity_thenItIsUpdated() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = prepareBasicAuthHeaders();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
//Create entity
ResponseEntity<Foo> response = restTemplate.exchange(fooService, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
assertThat(response.getBody().getId(), is(1L));
//Update entity
Foo updatedInstance = new Foo("newName");
updatedInstance.setId(1);
String resourceUrl = fooService + "/1";
restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
//Check that entity was updated
response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
Foo foo = response.getBody();
assertThat(foo.getId(), is(1L));
assertThat(foo.getName(), is(updatedInstance.getName()));
}
private RequestCallback requestCallback(Foo updatedInstace) {
return clientHttpRequest -> {
ObjectMapper mapper = new ObjectMapper();