Robert Strauch
05/02/2023, 6:42 AMWireMock.stubFor()
or WireMockExtension's wireMockExtension.stubFor()
. In the following @SpringBootTest
only wireMockExtension.stubFor()
seems to work. WireMock.stubFor()
gives a 404 and a message that there are no registered stubs. What's the difference between both variants and in which cases would one use one or the other?
Here is a sample test...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@WireMockTest
class WiremockSpringbootApplicationTests {
@Value("${remote.url}")
private String remoteUrl;
@RegisterExtension
static WireMockExtension wireMockExtension = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.build();
// set remote.url dynamically based on WireMock instance
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("remote.url", wireMockExtension::baseUrl);
}
@Test
void should_return_test() {
final WebClient webClient = WebClient.builder().baseUrl(remoteUrl).build();
// this stubbing works...
wireMockExtension.stubFor(get("/test")
.willReturn(aResponse().withBody("test")));
// ... this doesn't and gives a 404
// WireMock.stubFor(get("/test")
// .willReturn(aResponse().withBody("test")));
final String responseString = webClient.get().uri("/test")
.retrieve()
.bodyToMono(String.class)
.block();
Assertions.assertThat(responseString).isEqualTo("test");
}
}
Shruti Mishra
05/05/2023, 1:17 PM