1
我是從1.1到1.4,突然的最近升級的春天啓動的項目,爲「/健康」端點開始測試失敗MockRestServiceServer不按時健康端點更新restTemplate
@SpringBootTest
class HealthTest extends Specification {
@Autowired
RestTemplate thirdPartyRestTemplate
def 'should set health status based on third party service'() {
given:
MockRestServiceServer thirdPartyServerMock = MockRestServiceServer.createServer(thirdPartyRestTemplate)
thirdPartyServerMock
.expect(MockRestRequestMatchers.requestTo('/status'))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(thirdPartyServerResponse).body('{}'))
when:
def response = RestAssured.given().get('/health')
println(response.statusCode)
Map health = response.as(Map)
then:
thirdPartyServerMock.verify()
health == expectedHealth
where:
thirdPartyServerResponse | expectedHealth
HttpStatus.OK | [status: 'UP', thirdPartyServer: 'UP']
HttpStatus.SERVICE_UNAVAILABLE | [status: 'DOWN', thirdPartyServer: 'DOWN']
}
}
發生了什麼是:第一次測試總是通過,而第二次總是失敗。輸出爲200 200,如果順序顛倒,同樣的情況,所以
where:
thirdPartyServerResponse | expectedHealth
HttpStatus.SERVICE_UNAVAILABLE | [status: 'DOWN', thirdPartyServer: 'DOWN']
HttpStatus.OK | [status: 'UP', thirdPartyServer: 'UP']
這一次,它與503 503失敗如果我實際的REST調用這樣
when:
Thread.sleep(1000)
def response = RestAssured.given().get('/health')
前加入Thread.sleep代碼行
然後它每次都會通過!所以,Spring看起來像MockRestServiceServer
中的一些變化,並且需要一些時間來配置一個模擬(也許這是在單獨的線程中執行)。
有沒有人有類似的問題?如何繞過此Thread.sleep修復程序以及此行爲的解釋是什麼?