package com.ankurm.hsc; import com.ankurm.hsc.client.PostClient; import com.ankurm.hsc.model.Post; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.restclient.test.autoconfigure.RestClientTest; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestClient; import org.springframework.web.client.support.RestClientAdapter; import org.springframework.web.service.invoker.HttpServiceProxyFactory; import org.springframework.web.service.registry.ImportHttpServices; 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; /** * @RestClientTest next to an @ImportHttpServices group: what binds to the auto-configured * MockRestServiceServer and what does not. */ @RestClientTest(properties = "spring.http.serviceclient.slice.base-url=http://upstream.test") @Import(Step09RestClientSliceTest.SliceGroups.class) class Step09RestClientSliceTest { @Configuration(proxyBeanMethods = false) @ImportHttpServices(group = "slice", types = PostClient.class) static class SliceGroups { } @Autowired RestClient.Builder builder; @Autowired MockRestServiceServer server; private static final String JSON = "{\"id\":1,\"userId\":1,\"title\":\"From the mock\",\"body\":\"b\"}"; @Test void sliceWithHttpServiceGroup() { Transcript t = new Transcript("09-rest-client-test-slice.txt"); t.line("# a proxy built from the slice's own RestClient.Builder, which the mock server IS bound to"); PostClient viaBuilder = HttpServiceProxyFactory.builderFor( RestClientAdapter.create(builder.baseUrl("http://upstream.test").build())).build().createClient(PostClient.class); server.expect(requestTo("http://upstream.test/posts/1")).andRespond(withSuccess(JSON, MediaType.APPLICATION_JSON)); Post p = viaBuilder.findById(1); server.verify(); t.line("findById(1) -> %s", p); t.save(); assertThat(p.title()).isEqualTo("From the mock"); } }