MockRestServiceServer 没有及时为健康端点更新 restTemplate

MockRestServiceServer does not update restTemplate on time for health endpoint

我最近将 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 修复以及对此行为的解释是什么?

原来Spring为健康端点引入了缓存机制,默认缓存结果1秒。来自文档:

# Time to live for cached result, in milliseconds.    
endpoints.health.time-to-live=1000 

一旦我将配置更改为:

endpoints:
  health:
    time-to-live: 0

测试又开始通过了。