我正在尝试使用Wiremock拦截在ApplicationReadyEvent
上触发的HTTP调用。问题是此调用是在应用Wiremock规则之前进行的。所以这个API没有被嘲笑。
参见以下示例
public class OnApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent>{
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// in this pathe is being send a request
consulHealthCheckService.register();
}
}
存根在@Before
阶段配置,实际上在Servlet容器就绪后触发。实际上 - 在HTTP调用被激活后
@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")));
}
}
有没有办法如何存根给出http调用?请注意:我无法模拟实际触发呼叫的服务代码。
答案 0 :(得分:0)
您可以静态地在端口上创建WireMockRule
启动它,而不是使用WireMockServer
,并且甚至在此测试类完全初始化之前加载映射。如果这确实有效,您可以使用@AfterClass
方法确保服务器关闭。
如果您尝试并且在测试类初始化之前它仍在发出请求,那么您将必须弄清楚该请求何时/何地,并找到另一种方法来测试您的断言,因为它在测试之前被触发class甚至被初始化。