Merge pull request #11989 from anuragkumawat/JAVA-9809

JAVA-9809 Update tests in spring-resttemplate module
This commit is contained in:
kwoyke 2022-03-30 10:47:38 +02:00 committed by GitHub
commit 2cda833322
11 changed files with 202 additions and 117 deletions

View File

@ -39,8 +39,14 @@
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-provider-junit_2.11</artifactId>
<artifactId>pact-jvm-provider-junit5_2.12</artifactId>
<version>${pact.version}</version>
</dependency>
<dependency>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-consumer-junit5_2.12</artifactId>
<version>${pact.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
@ -112,6 +118,12 @@
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -263,7 +275,7 @@
<findbugs-maven-plugin.version>3.0.4</findbugs-maven-plugin.version>
<!-- okhttp -->
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
<pact.version>3.5.11</pact.version>
<pact.version>3.6.3</pact.version>
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<maven.version>3.7.0</maven.version>

View File

@ -1,9 +1,11 @@
package com.baeldung;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
import com.baeldung.resttemplate.RestTemplateConfigurationApplication;
@SpringBootTest(classes= RestTemplateConfigurationApplication.class)
public class SpringContextTest {
@Test

View File

@ -1,10 +1,8 @@
package com.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

View File

@ -1,12 +1,9 @@
package com.baeldung.client;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import com.baeldung.resttemplate.web.dto.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
@ -27,7 +24,7 @@ public class TestRestTemplateBasicLiveTest {
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
@BeforeEach
public void beforeTest() {
restTemplate = new RestTemplate();
}
@ -37,7 +34,7 @@ public class TestRestTemplateBasicLiveTest {
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));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -46,7 +43,7 @@ public class TestRestTemplateBasicLiveTest {
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));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -55,7 +52,7 @@ public class TestRestTemplateBasicLiveTest {
restTemplateBuilder.build();
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -65,7 +62,7 @@ public class TestRestTemplateBasicLiveTest {
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -73,7 +70,7 @@ public class TestRestTemplateBasicLiveTest {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -81,7 +78,7 @@ public class TestRestTemplateBasicLiveTest {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd").
getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -90,7 +87,7 @@ public class TestRestTemplateBasicLiveTest {
HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
// HEAD
@ -98,7 +95,7 @@ public class TestRestTemplateBasicLiveTest {
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL);
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
Assertions.assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
}
// POST

View File

@ -6,14 +6,10 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
import java.net.URI;
import com.baeldung.SpringTestConfig;
import com.baeldung.mock.EmployeeService;
import com.baeldung.resttemplate.web.model.Employee;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -21,15 +17,16 @@ import org.springframework.boot.test.context.SpringBootTest;
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.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import com.baeldung.SpringTestConfig;
import com.baeldung.resttemplate.web.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SpringTestConfig.class)
public class EmployeeServiceMockRestServiceServerUnitTest {
@ -45,7 +42,7 @@ public class EmployeeServiceMockRestServiceServerUnitTest {
private ObjectMapper mapper = new ObjectMapper();
@Before
@BeforeEach
public void init() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@ -63,7 +60,7 @@ public class EmployeeServiceMockRestServiceServerUnitTest {
Employee employee = empService.getEmployee("E001");
mockServer.verify();
Assert.assertEquals(emp, employee);
Assertions.assertEquals(emp, employee);
}
}

View File

@ -1,22 +1,21 @@
package com.baeldung.mock;
import com.baeldung.mock.EmployeeService;
import com.baeldung.resttemplate.web.model.Employee;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
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)
import com.baeldung.resttemplate.web.model.Employee;
@ExtendWith(MockitoExtension.class)
public class EmployeeServiceUnitTest {
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class);
@ -35,7 +34,7 @@ public class EmployeeServiceUnitTest {
Employee employee = empService.getEmployee("E001");
Assert.assertEquals(emp, employee);
Assertions.assertEquals(emp, employee);
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.pact;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.web.client.RestTemplate;
import au.com.dius.pact.consumer.MockServer;
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.model.RequestResponsePact;
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "test_provider", hostInterface="localhost")
public class PactConsumerDrivenContractUnitTest {
@Pact(provider="test_provider", consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return builder
.given("test GET")
.uponReceiving("GET REQUEST")
.path("/pact")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"condition\": true, \"name\": \"tom\"}")
.given("test POST")
.uponReceiving("POST REQUEST")
.method("POST")
.headers(headers)
.body("{\"name\": \"Michael\"}")
.path("/pact")
.willRespondWith()
.status(201)
.toPact();
}
@Test
@PactTestFor
void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody(MockServer mockServer) {
// when
ResponseEntity<String> response = new RestTemplate().getForEntity(mockServer.getUrl() + "/pact", String.class);
// then
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue();
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
// and
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String jsonBody = "{\"name\": \"Michael\"}";
// when
ResponseEntity<String> postResponse = new RestTemplate().exchange(mockServer.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class);
// then
assertThat(postResponse.getStatusCode().value()).isEqualTo(201);
}
}

View File

@ -1,35 +1,43 @@
package com.baeldung.pact;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.SpringApplication;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import com.baeldung.sampleapp.config.MainApplication;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
import au.com.dius.pact.provider.junit5.HttpTestTarget;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
@RunWith(PactRunner.class)
@Provider("test_provider")
@PactFolder("pacts")
@PactFolder("target/pacts")
public class PactProviderLiveTest {
@TestTarget
public final Target target = new HttpTarget("http", "localhost", 8082, "/spring-rest");
private static ConfigurableWebApplicationContext application;
@BeforeClass
@BeforeAll
public static void start() {
application = (ConfigurableWebApplicationContext) SpringApplication.run(MainApplication.class);
}
@BeforeEach
void before(PactVerificationContext context) {
context.setTarget(new HttpTestTarget("localhost", 8082, "/spring-rest"));
}
@TestTemplate
@ExtendWith(PactVerificationInvocationContextProvider.class)
void pactVerificationTestTemplate(PactVerificationContext context) {
context.verifyInteraction();
}
@State("test GET")
public void toGetState() {
}

View File

@ -2,12 +2,7 @@ package com.baeldung.resttemplate;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
import static com.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 static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.net.URI;
@ -16,8 +11,10 @@ import java.util.Set;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.dto.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
@ -44,7 +41,7 @@ public class RestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
@Before
@BeforeEach
public void beforeTest() {
restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
@ -57,7 +54,7 @@ public class RestTemplateBasicLiveTest {
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
final ResponseEntity<Foo> response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
@Test
@ -68,15 +65,15 @@ public class RestTemplateBasicLiveTest {
final ObjectMapper mapper = new XmlMapper();
final JsonNode root = mapper.readTree(response.getBody());
final JsonNode name = root.path("name");
assertThat(name.asText(), notNullValue());
Assertions.assertNotNull(name.asText());
}
@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));
Assertions.assertNotNull(foo.getName());
Assertions.assertEquals(foo.getId(), 1L);
}
// HEAD, OPTIONS
@ -84,7 +81,7 @@ public class RestTemplateBasicLiveTest {
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
assertTrue(httpHeaders.getContentType()
Assertions.assertTrue(httpHeaders.getContentType()
.includes(MediaType.APPLICATION_JSON));
}
@ -94,15 +91,15 @@ public class RestTemplateBasicLiveTest {
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"));
Assertions.assertNotNull(foo);
Assertions.assertEquals(foo.getName(), "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());
Assertions.assertNotNull(location);
}
@Test
@ -110,10 +107,10 @@ public class RestTemplateBasicLiveTest {
final Foo foo = new Foo("bar");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final Foo fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse.getName(), is("bar"));
Assertions.assertNotNull(fooResponse);
Assertions.assertEquals(fooResponse.getName(), "bar");
}
@Test
@ -121,7 +118,7 @@ public class RestTemplateBasicLiveTest {
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
Assertions.assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
// PUT
@ -146,7 +143,7 @@ public class RestTemplateBasicLiveTest {
// 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()));
Assertions.assertEquals(foo.getName(), updatedInstance.getName());
}
@Test
@ -156,7 +153,7 @@ public class RestTemplateBasicLiveTest {
// Create entity
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
// Update entity
final Foo updatedInstance = new Foo("newName");
@ -169,7 +166,7 @@ public class RestTemplateBasicLiveTest {
// 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()));
Assertions.assertEquals(foo.getName(), updatedInstance.getName());
}
// PATCH
@ -197,7 +194,7 @@ public class RestTemplateBasicLiveTest {
// 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()));
Assertions.assertEquals(foo.getName(), updatedResource.getName());
}
// DELETE
@ -206,7 +203,7 @@ public class RestTemplateBasicLiveTest {
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));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final String entityUrl = fooResourceUrl + "/" + response.getBody()
.getId();
@ -215,7 +212,7 @@ public class RestTemplateBasicLiveTest {
restTemplate.getForEntity(entityUrl, Foo.class);
fail();
} catch (final HttpClientErrorException ex) {
assertThat(ex.getStatusCode(), is(HttpStatus.INTERNAL_SERVER_ERROR));
Assertions.assertEquals(ex.getStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ -231,10 +228,10 @@ public class RestTemplateBasicLiveTest {
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
final String fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse, is("10"));
Assertions.assertNotNull(fooResponse);
Assertions.assertEquals(fooResponse, "10");
}
private HttpHeaders prepareBasicAuthHeaders() {

View File

@ -1,11 +1,8 @@
package com.baeldung.resttemplate;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@ -13,13 +10,13 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.RestTemplate;
import com.baeldung.sampleapp.config.RestClientConfig;
import com.baeldung.transfer.LoginForm;
@RunWith(SpringJUnit4ClassRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = RestClientConfig.class)
public class RestTemplateLiveTest {
@ -35,9 +32,9 @@ public class RestTemplateLiveTest {
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
assertThat(responseEntity.getHeaders()
Assertions.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
Assertions.assertEquals(responseEntity.getHeaders()
.get("Foo")
.get(0), is(equalTo("bar")));
.get(0), "bar");
}
}

View File

@ -1,27 +1,28 @@
package com.baeldung.web.handler;
import com.baeldung.resttemplate.web.exception.NotFoundException;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.model.Bar;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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 org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.context.junit.jupiter.SpringExtension;
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;
import com.baeldung.resttemplate.web.exception.NotFoundException;
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import com.baeldung.resttemplate.web.model.Bar;
@RunWith(SpringRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { NotFoundException.class, Bar.class })
@RestClientTest
public class RestTemplateResponseErrorHandlerIntegrationTest {
@ -29,10 +30,10 @@ public class RestTemplateResponseErrorHandlerIntegrationTest {
@Autowired private MockRestServiceServer server;
@Autowired private RestTemplateBuilder builder;
@Test(expected = NotFoundException.class)
@Test
public void givenRemoteApiCall_when404Error_thenThrowNotFound() {
Assert.assertNotNull(this.builder);
Assert.assertNotNull(this.server);
Assertions.assertNotNull(this.builder);
Assertions.assertNotNull(this.server);
RestTemplate restTemplate = this.builder
.errorHandler(new RestTemplateResponseErrorHandler())
@ -43,7 +44,8 @@ public class RestTemplateResponseErrorHandlerIntegrationTest {
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
Assertions.assertThrows(NotFoundException.class, () -> {
Bar response = restTemplate.getForObject("/bars/4242", Bar.class);
this.server.verify();
});
}
}