BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,16 @@
package org.baeldung;
import org.baeldung.resttemplate.RestTemplateConfigurationApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateConfigurationApplication.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,16 @@
package org.baeldung;
import org.baeldung.resttemplate.RestTemplateConfigurationApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateConfigurationApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,19 @@
package org.baeldung;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.baeldung")
public class SpringTestConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@@ -0,0 +1,5 @@
package org.baeldung.client;
public interface Consts {
int APPLICATION_PORT = 8082;
}
@@ -0,0 +1,123 @@
package org.baeldung.client;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import org.baeldung.resttemplate.web.dto.Foo;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import okhttp3.Request;
import okhttp3.RequestBody;
public class TestRestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos";
private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd";
private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest";
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
}
// GET
@Test
public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.build();
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd").
getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate.
HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
// HEAD
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL);
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenService_whenPostForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
// PUT
@Test
public void givenService_whenPutForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
}
@@ -0,0 +1,109 @@
package org.baeldung.resttemplate;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class LargeFileDownloadIntegrationTest {
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
RestTemplate restTemplate;
@Before
public void setUp() {
restTemplate = new RestTemplate();
}
@Test
public void givenResumableUrl_whenUrlCalledByHeadOption_thenExpectHeadersAvailable() {
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
Assertions
.assertThat(headers.get("Accept-Ranges"))
.contains("bytes");
Assertions
.assertThat(headers.getContentLength())
.isGreaterThan(0);
}
@Test
public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() {
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
long contentLength = headers.getContentLength();
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isEqualTo(contentLength);
}
@Test
public void givenResumableUrl_whenDownloadRange_thenExpectFileSizeEqualOrLessThanRange() {
int range = 10;
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isLessThanOrEqualTo(range);
}
@Test
public void givenResumableUrl_whenPauseDownloadAndResume_thenExpectCorrectFileSize() {
int range = 10;
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
long contentLength = headers.getContentLength();
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isLessThanOrEqualTo(range);
restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
.getHeaders()
.set("Range", String.format("bytes=%d-%d", file.length(), contentLength)), clientHttpResponse -> {
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file, true));
return file;
});
Assertions
.assertThat(file.length())
.isEqualTo(contentLength);
}
}
@@ -0,0 +1,272 @@
package org.baeldung.resttemplate;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Set;
import org.baeldung.resttemplate.web.dto.Foo;
import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.common.base.Charsets;
public class RestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
// restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
}
// GET
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
final ResponseEntity<Foo> response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
final RestTemplate template = new RestTemplate();
final ResponseEntity<String> response = template.getForEntity(fooResourceUrl + "/1", String.class);
final ObjectMapper mapper = new XmlMapper();
final JsonNode root = mapper.readTree(response.getBody());
final JsonNode name = root.path("name");
assertThat(name.asText(), notNullValue());
}
@Test
public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException {
final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
assertThat(foo.getName(), notNullValue());
assertThat(foo.getId(), is(1L));
}
// HEAD, OPTIONS
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
assertTrue(httpHeaders.getContentType()
.includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
}
@Test
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final URI location = restTemplate.postForLocation(fooResourceUrl, request, Foo.class);
assertThat(location, notNullValue());
}
@Test
public void givenFooService_whenPostResource_thenResourceIsCreated() {
final Foo foo = new Foo("bar");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final Foo fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse.getName(), is("bar"));
}
@Test
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
// PUT
@Test
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
assertThat(foo.getName(), is(updatedInstance.getName()));
}
@Test
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final 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
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(response.getBody()
.getId());
final 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);
final Foo foo = response.getBody();
assertThat(foo.getName(), is(updatedInstance.getName()));
}
// PATCH
@Test
public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedResource = new Foo("newName");
updatedResource.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers);
final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
final RestTemplate template = new RestTemplate(requestFactory);
template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
template.patchForObject(resourceUrl, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
assertThat(foo.getName(), is(updatedResource.getName()));
}
// DELETE
@Test
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
final Foo foo = new Foo("remove me");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final String entityUrl = fooResourceUrl + "/" + response.getBody()
.getId();
restTemplate.delete(entityUrl);
try {
restTemplate.getForEntity(entityUrl, Foo.class);
fail();
} catch (final HttpClientErrorException ex) {
assertThat(ex.getStatusCode(), is(HttpStatus.INTERNAL_SERVER_ERROR));
}
}
@Test
public void givenFooService_whenFormSubmit_thenResourceIsCreated() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "10");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final String fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse, is("10"));
}
private HttpHeaders prepareBasicAuthHeaders() {
final HttpHeaders headers = new HttpHeaders();
final String encodedLogPass = getBase64EncodedLogPass();
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
return headers;
}
private String getBase64EncodedLogPass() {
final String logPass = "user1:user1Pass";
final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
return new String(authHeaderBytes, Charsets.US_ASCII);
}
private RequestCallback requestCallback(final Foo updatedInstance) {
return clientHttpRequest -> {
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
clientHttpRequest.getHeaders()
.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
clientHttpRequest.getHeaders()
.add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
};
}
// Simply setting restTemplate timeout using ClientHttpRequestFactory
ClientHttpRequestFactory getClientHttpRequestFactory() {
final int timeout = 5;
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
return clientHttpRequestFactory;
}
}
@@ -0,0 +1,97 @@
package org.baeldung.resttemplate.postjson;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.net.URI;
import org.baeldung.resttemplate.RestTemplateConfigurationApplication;
import org.baeldung.resttemplate.web.dto.Person;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateConfigurationApplication.class)
public class PersonAPILiveTest {
private static String createPersonUrl;
private static String updatePersonUrl;
private static RestTemplate restTemplate;
private static HttpHeaders headers;
private final ObjectMapper objectMapper = new ObjectMapper();
private static JSONObject personJsonObject;
@BeforeClass
public static void runBeforeAllTestMethods() throws JSONException {
createPersonUrl = "http://localhost:8082/spring-rest/createPerson";
updatePersonUrl = "http://localhost:8082/spring-rest/updatePerson";
restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
personJsonObject = new JSONObject();
personJsonObject.put("id", 1);
personJsonObject.put("name", "John");
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForObject_thenResponseBodyIsNotNull() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
String personResultAsJsonStr = restTemplate.postForObject(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(personResultAsJsonStr);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(personResultAsJsonStr);
assertNotNull(root);
assertNotNull(root.path("name")
.asText());
assertNotNull(person);
assertNotNull(person.getName());
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForEntity_thenResponseBodyIsNotNull() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
ResponseEntity<String> responseEntityStr = restTemplate.postForEntity(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(responseEntityStr.getBody());
ResponseEntity<Person> responseEntityPerson = restTemplate.postForEntity(createPersonUrl, request, Person.class);
assertNotNull(responseEntityStr.getBody());
assertNotNull(root.path("name")
.asText());
assertNotNull(responseEntityPerson.getBody());
assertNotNull(responseEntityPerson.getBody()
.getName());
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForLocation_thenResponseBodyIsTheLocationHeader() throws JsonProcessingException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
URI locationHeader = restTemplate.postForLocation(updatePersonUrl, request);
assertNotNull(locationHeader);
}
}
@@ -0,0 +1,49 @@
package org.baeldung.web.handler;
import org.baeldung.resttemplate.web.exception.NotFoundException;
import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import org.baeldung.resttemplate.web.model.Bar;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { NotFoundException.class, Bar.class })
@RestClientTest
public class RestTemplateResponseErrorHandlerIntegrationTest {
@Autowired private MockRestServiceServer server;
@Autowired private RestTemplateBuilder builder;
@Test(expected = NotFoundException.class)
public void givenRemoteApiCall_when404Error_thenThrowNotFound() {
Assert.assertNotNull(this.builder);
Assert.assertNotNull(this.server);
RestTemplate restTemplate = this.builder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
this.server
.expect(ExpectedCount.once(), requestTo("/bars/4242"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
Bar response = restTemplate.getForObject("/bars/4242", Bar.class);
this.server.verify();
}
}
@@ -0,0 +1,67 @@
package org.baeldung.web.service;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import java.net.URI;
import org.baeldung.SpringTestConfig;
import org.baeldung.resttemplate.web.model.Employee;
import org.baeldung.resttemplate.web.service.EmployeeService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringTestConfig.class)
public class EmployeeServiceMockRestServiceServerUnitTest {
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class);
@Autowired
private EmployeeService empService;
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
private ObjectMapper mapper = new ObjectMapper();
@Before
public void init() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_shouldReturnMockedObject() throws Exception {
Employee emp = new Employee("E001", "Eric Simmons");
mockServer.expect(ExpectedCount.once(),
requestTo(new URI("http://localhost:8080/employee/E001")))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(mapper.writeValueAsString(emp)));
Employee employee = empService.getEmployee("E001");
mockServer.verify();
Assert.assertEquals(emp, employee);
}
}
@@ -0,0 +1,42 @@
package org.baeldung.web.service;
import org.baeldung.resttemplate.web.model.Employee;
import org.baeldung.resttemplate.web.service.EmployeeService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceUnitTest {
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class);
@Mock
private RestTemplate restTemplate;
@InjectMocks
private EmployeeService empService = new EmployeeService();
@Test
public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception {
Employee emp = new Employee("E001", "Eric Simmons");
Mockito.when(restTemplate.getForEntity("http://localhost:8080/employee/E001", Employee.class))
.thenReturn(new ResponseEntity(emp, HttpStatus.OK));
Employee employee = empService.getEmployee("E001");
Assert.assertEquals(emp, employee);
}
}