From 9c6cfa333feb6452ff8dac32cde13e488d6538a3 Mon Sep 17 00:00:00 2001 From: Dmitry Zinkevich Date: Fri, 28 Aug 2015 09:26:25 +0300 Subject: [PATCH] [RestTemplate] Create unit tests for GET and POST methods --- .../org/baeldung/persistence/model/Owner.java | 25 ++++ .../persistence/model/Repository.java | 35 +++++ .../org/baeldung/persistence/model/User_.java | 2 + .../web/controller/FooController.java | 8 +- .../baeldung/client/RestTemplateLiveTest.java | 131 ++++++++++++++++++ 5 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java create mode 100644 spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java create mode 100644 spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java new file mode 100644 index 0000000000..cce00054de --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Owner.java @@ -0,0 +1,25 @@ +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; + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java new file mode 100644 index 0000000000..89372fa7a7 --- /dev/null +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/Repository.java @@ -0,0 +1,35 @@ +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; + } +} diff --git a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java index c7b6ba2de8..b705c51ff8 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/persistence/model/User_.java @@ -5,7 +5,9 @@ import javax.persistence.metamodel.StaticMetamodel; @StaticMetamodel(User.class) public class User_ { + public static volatile SingularAttribute id; public static volatile SingularAttribute firstName; public static volatile SingularAttribute lastName; public static volatile SingularAttribute age; + public static volatile SingularAttribute email; } \ No newline at end of file diff --git a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index fdf0157230..091c452731 100644 --- a/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-security-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -85,11 +85,15 @@ public class FooController { @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) - public void create(@RequestBody final Foo resource, final HttpServletResponse response) { + @ResponseBody + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); - final Long idOfCreatedResource = service.create(resource).getId(); + Foo foo = service.create(resource); + final Long idOfCreatedResource = foo.getId(); eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); + + return foo; } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) diff --git a/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java new file mode 100644 index 0000000000..0265124ef3 --- /dev/null +++ b/spring-security-rest-full/src/test/java/org/baeldung/client/RestTemplateLiveTest.java @@ -0,0 +1,131 @@ +package org.baeldung.client; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.config.RequestConfig; +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.spring.PersistenceConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +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.RestTemplate; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }) +public class RestTemplateLiveTest { + + RestTemplate restTemplate; + private List> messageConverters; + private final String userReposUrl = "https://api.github.com/users/eugenp/repos"; + private final String repoUrl = "https://api.github.com/repos/eugenp/tutorials"; + + @Before + public void beforeTest() { + restTemplate = new RestTemplate(); + + messageConverters = new ArrayList<>(); + MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); + jsonMessageConverter.setObjectMapper(new ObjectMapper()); + messageConverters.add(jsonMessageConverter); + } + + @Test + public void givenValidEndpoint_whenSendGetForRequestEntity_thenStatusOk() throws IOException { + ResponseEntity response = restTemplate.getForEntity(userReposUrl, String.class); + assertThat(response.getStatusCode(), is(HttpStatus.OK)); + } + + @Test + public void givenRepoEndpoint_whenSendGetForRestEntity_thenReceiveCorrectRepoJson() throws IOException { + ResponseEntity response = restTemplate.getForEntity(repoUrl, String.class); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(response.getBody()); + + JsonNode name = root.path("name"); + assertThat(name.asText(), is("tutorials")); + + JsonNode owner = root.path("owner").path("login"); + assertThat(owner.asText(), is("eugenp")); + } + + @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")); + } + + @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 request = new HttpEntity<>(new Foo("bar")); + Foo foo = restTemplate.postForObject(fooService, 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 request = new HttpEntity<>(new Foo("bar")); + Foo firstInstance = restTemplate.postForObject(fooService, request, Foo.class); + Foo secondInstance = restTemplate.postForObject(fooService, request, Foo.class); + assertThat(firstInstance, notNullValue()); + assertThat(secondInstance, notNullValue()); + assertThat(firstInstance, not(secondInstance)); + } + + private ClientHttpRequestFactory getClientHttpRequestFactory() { + int timeout = 5; + RequestConfig config = RequestConfig.custom() + .setConnectTimeout(timeout * 1000) + .setConnectionRequestTimeout(timeout * 1000) + .setSocketTimeout(timeout * 1000).build(); + + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), + new UsernamePasswordCredentials("user1", "user1Pass")); + + CloseableHttpClient client = HttpClientBuilder.create() + .setDefaultRequestConfig(config) + .setDefaultCredentialsProvider(credentialsProvider).build(); + + return new HttpComponentsClientHttpRequestFactory(client); + } +}