我最近将Spring启动项目从1.1升级到1.4,突然之间,'/ health'端点的测试开始失败
@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调用之前添加Thread.sleep行像这样
when:
Thread.sleep(1000)
def response = RestAssured.given().get('/health')
然后每次都过去了!因此,看起来Spring在MockRestServiceServer
中引入了一些更改,并且需要一些时间来配置模拟(可能现在在单独的线程中执行)。
有没有人有类似的问题?如何绕过这个Thread.sleep修复程序以及这种行为的解释是什么?
答案 0 :(得分:0)
事实证明,Spring为健康端点引入了缓存机制,默认情况下,缓存结果为1秒。来自文档:
# Time to live for cached result, in milliseconds.
endpoints.health.time-to-live=1000
我将配置更改为:
endpoints:
health:
time-to-live: 0
测试再次开始。