2017-08-14 45 views
3

如何測試AsyncRestTemplate請求並避免java.lang.IllegalStateException: Expectations already declared異常?針對單個測試用例引發的異常不一致。從幾個下游系統防止期望在測試AsyncRestTemplate時已經聲明異常

Java.lang.IllegalStateException: Expectations already declared at org.springframework.util.Assert.state(Assert.java:70) at org.springframework.test.web.client.SimpleRequestExpectationManager.afterExpectationsDeclared(SimpleRequestExpectationManager.java:47) at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:73) at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:289) at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:94) at org.springframework.mock.http.client.MockAsyncClientHttpRequest.executeAsync(MockAsyncClientHttpRequest.java:50) at org.springframework.web.client.AsyncRestTemplate.doExecute(AsyncRestTemplate.java:503) at org.springframework.web.client.AsyncRestTemplate.execute(AsyncRestTemplate.java:463) at org.springframework.web.client.AsyncRestTemplate.getForEntity(AsyncRestTemplate.java:217) at com.company.MainClient.getStatus(MainClient.java:151) at com.company.MainController.status(MainController.java:88)

應用聚集數據。要求它提出幾個請求。其中一些請求是異步的,Future將在稍後處理。其他請求通過立即呼叫asyncRestTemplateResponse.get()來阻止主線程。

下面的測試將導致錯誤:

Note: Server is MockRestServiceServer

@Test 
public void statusTest() throws Exception { 
    cServer.expect(once(),requestTo("http://localhost:8080/heartbeat")) 
     .andRespond(withSuccess(cStatus, MediaType.APPLICATION_JSON)); 

    cpServer.expect(once(),requestTo("http://localhost:8081/status")) 
      .andRespond(withSuccess(cpStatus, MediaType.APPLICATION_JSON)); 

    tServer.expect(once(),requestTo("http://localhost:3030/check")) 
      .andRespond(withSuccess(tStatus, MediaType.TEXT_PLAIN)); 

    tServer.expect(once(),requestTo("http://localhost:3031/check")) 
      .andRespond(withSuccess(tStatus, MediaType.TEXT_PLAIN)); 

    tServer.expect(once(),requestTo("http://localhost:3032/check")) 
      .andRespond(withSuccess(tStatus, MediaType.TEXT_PLAIN)); 

    mockMvc.perform(get("/status").with(user(USERNAME).password(PASSWORD).roles("T_CLIENT"))) 
      .andDo(print()).andExpect(status().isOk()) 
      .andExpect(jsonPath("$.code").value("200")) 
      .andExpect(jsonPath("$.appDescription").value("Main Service")) 
      .andExpect(jsonPath("$.gateways[?(@.responseCode =~ /200/)]").isArray()); 

    //Test without basic auth 
    mockMvc.perform(get("/status")) 
      .andDo(print()).andExpect(status().isUnauthorized()); 
} 
+1

FWIW,我收到了類似的失敗,您可能會感興趣:https://jira.spring.io/browse/SPR-16132 –

回答