I am trying to use Wiremock to intercept an HTTP call fired on ApplicationReadyEvent. The issue is that this call is made before a Wiremock rules being applied. So this API is no mocked.
See following example
public class OnApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent>{
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// in this pathe is being send a request
consulHealthCheckService.register();
}
}
The stubbing is configured in @Before phase, which is actually triggered once a Servlet container is ready. So actually - after the HTTP call is fired
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ConsulApplication.class)
public class ConsulApplicationTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(Agent.DEFAULT_PORT );
@Before
public void setup(){
// is being executed after the http call was fired
stubFor(get(anyUrl()).willReturn(aResponse().withStatus(HttpStatus.OK.value())));
stubFor(put(urlEqualTo("/agent/service/register"))
.willReturn(aResponse()
.withStatus(HttpStatus.OK.value())
.withHeader("Content-Type", APPLICATION_JSON_VALUE)
));
}
@Test
public void shouldRegisterServiceOnApplicationStartup(){
verify( putRequestedFor(urlEqualTo("/agent/service/register")));
}
}
Is there any way how to stub given http call? Please note: Iam not able to mock the service code which actually triggers the call.
Instead of using the WireMockRule, you could statically create a WireMockServer start it on the port, and load the mappings even before this test class is fully initialized. IF this does work, you could ensure the server is shutdown in an @AfterClass method.
If you try that and it's still making the request before your test class is initialized, then you'll have to figure out when/where that request is made and find another way to test your assertion as it's being fired before the test class is even initialized.