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; /** * {@link EmployeeHttpInterface} has no class {@code @RestClientTest} can point at directly - it * is a bare interface, and the real bean only exists because {@link AppConfig}'s * {@code @Bean} method builds it from an {@code HttpServiceProxyFactory}. Passing the * {@code @Configuration} class itself as the slice's "component" is what gets that bean (and * the underlying {@code RestClient} it is built from) into the test context at all; the mocking * code underneath is otherwise identical to {@link RestClientEmployeeTest}. */ @RestClientTest(components = AppConfig.class) class HttpInterfaceClientTest { @Autowired private MockRestServiceServer mockServer; @Autowired private EmployeeHttpInterface employeeHttpInterface; @Autowired private ObjectMapper objectMapper; @Test void whenGetEmployeeById_thenHttpInterfaceReturnsEmployee() throws Exception { Employee mockEmployee = new Employee(3, "Daniel", "O", "daniel@example.com"); String employeeJson = objectMapper.writeValueAsString(mockEmployee); mockServer.expect(requestTo("http://hr-api.example.com/employees/3")) .andRespond(withSuccess(employeeJson, MediaType.APPLICATION_JSON)); Employee result = employeeHttpInterface.getEmployeeById(3); assertThat(result).isNotNull(); assertThat(result.id()).isEqualTo(3); assertThat(result.firstName()).isEqualTo("Daniel"); mockServer.verify(); Capture.write("04-http-interface-client.txt", "A declarative @HttpExchange interface client, mocked the same way as a hand-written one", "requestTo(\"http://hr-api.example.com/employees/3\") -> 200 OK " + employeeJson + "\nresult = " + result); } }