2017-04-10 43 views
2

我試圖使用Wiremock來攔截在ApplicationReadyEvent上觸發的HTTP調用。問題在於,此調用是在應用Wiremock規則之前完成的。所以這個API沒有被嘲笑。如何模擬在ApplicationReadyEvent上觸發的HTTP調用

參見下面的示例

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調用之後?請注意:Iam不能模擬實際觸發呼叫的服務代碼。

回答

0

而不是使用WireMockRule,您可以靜態創建一個WireMockServer在端口上啓動它,甚至在此測試類完全初始化之前加載映射。如果這確實起作用,則可以確保服務器在@AfterClass方法中關閉。

如果你嘗試這樣做,並且在你的測試類被初始化之前仍然發出請求,那麼你必須弄清楚何時/何地發出了請求,並找到另一種方法來測試你的斷言,因爲它在測試類甚至被初始化。