JAVA-3537: Move spring-rest-simple into spring-web-modules
This commit is contained in:
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung;
|
||||
|
||||
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 = Application.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.repository;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.web.dto.Book;
|
||||
|
||||
public class BookRepositoryUnitTest {
|
||||
|
||||
private BookRepository repository;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
repository = new BookRepository();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoBooks_WhenFindById_ThenReturnEmptyOptional() {
|
||||
assertFalse(repository.findById(1).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneMatchingBook_WhenFindById_ThenReturnEmptyOptional() {
|
||||
|
||||
long id = 1;
|
||||
Book expected = bookWithId(id);
|
||||
|
||||
repository.add(expected);
|
||||
|
||||
Optional<Book> found = repository.findById(id);
|
||||
|
||||
assertTrue(found.isPresent());
|
||||
assertEquals(expected, found.get());
|
||||
}
|
||||
|
||||
private static Book bookWithId(long id) {
|
||||
Book book = new Book();
|
||||
book.setId(id);
|
||||
return book;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNonMatchingBook_WhenFindById_ThenReturnEmptyOptional() {
|
||||
|
||||
long id = 1;
|
||||
Book expected = bookWithId(id);
|
||||
|
||||
repository.add(expected);
|
||||
|
||||
Optional<Book> found = repository.findById(id + 1);
|
||||
|
||||
assertFalse(found.isPresent());
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.baeldung.Application;
|
||||
import com.baeldung.repository.BookRepository;
|
||||
import com.baeldung.web.dto.Book;
|
||||
import com.baeldung.web.error.ApiErrorResponse;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest(BookController.class)
|
||||
@ComponentScan(basePackageClasses = Application.class)
|
||||
public class BookControllerIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@MockBean
|
||||
private BookRepository repository;
|
||||
|
||||
@Test
|
||||
public void givenNoExistingBooks_WhenGetBookWithId1_ThenErrorReturned() throws Exception {
|
||||
|
||||
long id = 1;
|
||||
|
||||
doReturn(Optional.empty()).when(repository).findById(eq(id));
|
||||
|
||||
mvc.perform(get("/api/book/{id}", id))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(content().json(MAPPER.writeValueAsString(new ApiErrorResponse("error-0001", "No book found with ID " + id))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMatchingBookExists_WhenGetBookWithId1_ThenBookReturned() throws Exception {
|
||||
|
||||
long id = 1;
|
||||
Book book = book(id, "foo", "bar");
|
||||
|
||||
doReturn(Optional.of(book)).when(repository).findById(eq(id));
|
||||
|
||||
mvc.perform(get("/api/book/{id}", id))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().json(MAPPER.writeValueAsString(book)));
|
||||
}
|
||||
|
||||
private static Book book(long id, String title, String author) {
|
||||
|
||||
Book book = new Book();
|
||||
|
||||
book.setId(id);
|
||||
book.setTitle(title);
|
||||
book.setAuthor(author);
|
||||
|
||||
return book;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.web.controller.mediatypes;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({ "com.baeldung.web", "com.baeldung.repository" })
|
||||
public class TestConfig {
|
||||
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.jayway.restassured.RestAssured;
|
||||
|
||||
public class RequestMappingLiveTest {
|
||||
private static String BASE_URI = "http://localhost:8082/spring-rest/ex/";
|
||||
|
||||
@Test
|
||||
public void givenSimplePath_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Simple Get some Foos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.post(BASE_URI + "foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Post some Foos"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.header("key", "val")
|
||||
.get(BASE_URI + "foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get some Foos with Header"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleHeaders_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.headers("key1", "val1", "key2", "val2")
|
||||
.get(BASE_URI + "foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get some Foos with Header"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAcceptHeader_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("application/json")
|
||||
.get(BASE_URI + "foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(containsString("Get some Foos with Header New"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathVariable_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "foos/1")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get a specific Foo with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplePathVariable_whenGetFoos_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "foos/1/bar/2")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get a specific Bar with id=2 from a Foo with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathVariable_whenGetBars_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "bars/1")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get a specific Bar with id=1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParams_whenGetBars_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "bars?id=100&second=something")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Get a specific Bar with id=100"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFoosOrBars_thenOk() {
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "advanced/foos")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Advanced - Get some Foos or Bars"));
|
||||
RestAssured.given()
|
||||
.accept("text/html")
|
||||
.get(BASE_URI + "advanced/bars")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(equalTo("Advanced - Get some Foos or Bars"));
|
||||
}
|
||||
}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
package com.baeldung.web.test;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64;
|
||||
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.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.baeldung.web.dto.Foo;
|
||||
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:8082/spring-rest/foos";
|
||||
|
||||
@Before
|
||||
public void beforeTest() {
|
||||
restTemplate = new RestTemplate();
|
||||
// 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);
|
||||
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 = getSimpleClientHttpRequestFactory();
|
||||
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.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
@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", "1");
|
||||
|
||||
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("1"));
|
||||
}
|
||||
|
||||
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 getSimpleClientHttpRequestFactory() {
|
||||
final int timeout = 5;
|
||||
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
|
||||
return clientHttpRequestFactory;
|
||||
}
|
||||
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.config.converter.KryoHttpMessageConverter;
|
||||
import com.baeldung.web.dto.Foo;
|
||||
import com.baeldung.web.dto.FooProtos;
|
||||
|
||||
/**
|
||||
* Integration Test class. Tests methods hits the server's rest services.
|
||||
*/
|
||||
public class SpringHttpMessageConvertersLiveTest {
|
||||
|
||||
private static String BASE_URI = "http://localhost:8082/spring-rest/";
|
||||
|
||||
/**
|
||||
* Without specifying Accept Header, uses the default response from the
|
||||
* server (in this case json)
|
||||
*/
|
||||
@Test
|
||||
public void whenRetrievingAFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
final Foo resource = restTemplate.getForObject(URI, Foo.class, "1");
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingXml_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingXml_whenWritingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
final Foo resource = new Foo(4, "jason");
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
|
||||
headers.setContentType((MediaType.APPLICATION_XML));
|
||||
final HttpEntity<Foo> entity = new HttpEntity<Foo>(resource, headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.PUT, entity, Foo.class, resource.getId());
|
||||
final Foo fooResponse = response.getBody();
|
||||
|
||||
Assert.assertEquals(resource.getId(), fooResponse.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter()));
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<FooProtos.Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1");
|
||||
final FooProtos.Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenConsumingKryo_whenReadingTheFoo_thenCorrect() {
|
||||
final String URI = BASE_URI + "foos/{id}";
|
||||
|
||||
final RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setMessageConverters(Arrays.asList(new KryoHttpMessageConverter()));
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Arrays.asList(KryoHttpMessageConverter.KRYO));
|
||||
final HttpEntity<String> entity = new HttpEntity<String>(headers);
|
||||
|
||||
final ResponseEntity<Foo> response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1");
|
||||
final Foo resource = response.getBody();
|
||||
|
||||
assertThat(resource, notNullValue());
|
||||
}
|
||||
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.baeldung.web.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
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<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.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<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.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<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.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);
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.web.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public final class HTTPLinkHeaderUtil {
|
||||
|
||||
private HTTPLinkHeaderUtil() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
/**
|
||||
* ex. <br>
|
||||
* https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", <https://api.github.com/users/steveklabnik/gists?page=3>; rel="last"
|
||||
*/
|
||||
public static List<String> extractAllURIs(final String linkHeader) {
|
||||
Preconditions.checkNotNull(linkHeader);
|
||||
|
||||
final List<String> linkHeaders = Lists.newArrayList();
|
||||
final String[] links = linkHeader.split(", ");
|
||||
for (final String link : links) {
|
||||
final int positionOfSeparator = link.indexOf(';');
|
||||
linkHeaders.add(link.substring(1, positionOfSeparator - 1));
|
||||
}
|
||||
|
||||
return linkHeaders;
|
||||
}
|
||||
|
||||
public static String extractURIByRel(final String linkHeader, final String rel) {
|
||||
if (linkHeader == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String uriWithSpecifiedRel = null;
|
||||
final String[] links = linkHeader.split(", ");
|
||||
String linkRelation = null;
|
||||
for (final String link : links) {
|
||||
final int positionOfSeparator = link.indexOf(';');
|
||||
linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim();
|
||||
if (extractTypeOfRelation(linkRelation).equals(rel)) {
|
||||
uriWithSpecifiedRel = link.substring(1, positionOfSeparator - 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return uriWithSpecifiedRel;
|
||||
}
|
||||
|
||||
static Object extractTypeOfRelation(final String linkRelation) {
|
||||
final int positionOfEquals = linkRelation.indexOf('=');
|
||||
return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* ex. <br>
|
||||
* https://api.github.com/users/steveklabnik/gists?page=2>; rel="next"
|
||||
*/
|
||||
public static String extractSingleURI(final String linkHeader) {
|
||||
Preconditions.checkNotNull(linkHeader);
|
||||
final int positionOfSeparator = linkHeader.indexOf(';');
|
||||
|
||||
return linkHeader.substring(1, positionOfSeparator - 1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user