Add rest-client-test module: @RestClientTest on Boot 4.1, Jackson 3 by default, and the RestClient-vs-RestTemplate root-URI matching trap (post #49)
This commit is contained in:
+52
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.restclienttest;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.restclient.test.autoconfigure.RestClientTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.client.MockRestServiceServer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
|
||||
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
|
||||
|
||||
/**
|
||||
* Same job, built on {@code RestTemplate} instead of {@code RestClient}.
|
||||
* {@code @RestClientTest} auto-configures a {@code RestTemplateBuilder} too, so any
|
||||
* {@code RestTemplate} built from it is wired through the same {@code MockRestServiceServer} -
|
||||
* the mocking code below is identical to {@link RestClientEmployeeTest}'s, line for line.
|
||||
*/
|
||||
@RestClientTest(EmployeeTemplateClient.class)
|
||||
class RestTemplateEmployeeTest {
|
||||
|
||||
@Autowired
|
||||
private MockRestServiceServer mockServer;
|
||||
|
||||
@Autowired
|
||||
private EmployeeTemplateClient employeeTemplateClient;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Test
|
||||
void whenGetEmployeeById_thenReturnsEmployee() throws Exception {
|
||||
Employee mockEmployee = new Employee(2, "Priya", "V", "[email protected]");
|
||||
String employeeJson = objectMapper.writeValueAsString(mockEmployee);
|
||||
|
||||
mockServer.expect(requestTo("/employees/2"))
|
||||
.andRespond(withSuccess(employeeJson, MediaType.APPLICATION_JSON));
|
||||
|
||||
Employee result = employeeTemplateClient.getEmployeeById(2);
|
||||
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.id()).isEqualTo(2);
|
||||
assertThat(result.firstName()).isEqualTo("Priya");
|
||||
|
||||
mockServer.verify();
|
||||
|
||||
Capture.write("02-resttemplate-same-mocking-code.txt",
|
||||
"RestTemplate-based EmployeeTemplateClient, identical MockRestServiceServer code",
|
||||
"requestTo(\"/employees/2\") -> 200 OK " + employeeJson + "\nresult = " + result);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user