As far as I know, there is no annotation available that automatically configures an HTTP interface client for Spring Boot Test slice testing.
Currently, I am implementing my HTTP interface client tests like this :
@RestClientTest(MyClient.class)
class MyClassTest {
private static final String SERVICE_URL = "https://external.service.url";
@Autowired
private RestTemplateBuilder restTemplateBuilder;
private MyClient client;
private MockRestServiceServer server;
@BeforeEach
void beforeEach() {
if (client == null) {
RestTemplate restTemplate = restTemplateBuilder.build();
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(SERVICE_URL));
client = HttpServiceProxyFactory
.builderFor(RestTemplateAdapter.create(restTemplate))
.build()
.createClient(MyClient.class);
server = MockRestServiceServer.bindTo(restTemplate).build();
}
}
@Test
void myTest() {
server.expect(requestTo(SERVICE_URL + "/ping")
...
}
}
I suggest to make the AutoConfigureWebClient annotation evolve and add two new parameters :
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ImportAutoConfiguration
@PropertyMapping("spring.test.webclient")
public @interface AutoConfigureWebClient {
/**
* If a {@link RestTemplate} bean should be registered. Defaults to {@code false} with
* the assumption that the {@link RestTemplateBuilder} will be used.
* @return if a {@link RestTemplate} bean should be added.
*/
boolean registerRestTemplate() default false;
/**
* The HTTP service to create a proxy for
*
* @return the class of the HTTP service
*/
Class<?> value();
/**
* The based url that will be used by the proxy
*
* @return the based url
*/
String url() default "";
}
As a result, developers will be able to autoconfigure their Http interface client in their testing class like this :
@RestClientTest(MyClient.class)
@AutoConfigureWebClient(value = MyClient.class, url = SERVICE_URL)
class MyClassTest {
static final String SERVICE_URL = "https://external.service.url";
@Autowired
private MyClient client;
@Autowired
private MockRestServiceServer server;
@Test
void myTest() {
server.expect(requestTo(SERVICE_URL + "/ping")
...
}
}
I would be glad to open a pull request if this new feature suits you.
Comment From: bclozel
Duplicates #31337
Comment From: mathieu-amblard
Hi @bclozel , Should I post a comment in #31337 or the testing part is already taken into account in that issue ? I have seen this issue before opening mine but I did not see anything regarding tests... Thank you in advance for the clarifications
Comment From: bclozel
@mathieu-amblard Yes I think considering the test aspects there should be a good idea. In the end we can choose to tackle it separately but I think design considerations should be discussed there. We can always reopen this one if we think it's worth it.
Comment From: mathieu-amblard
I see, thank you very much @bclozel