2016-11-30 23 views
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修复程序以及此行为的解释是什么?

回答

0

事实证明,Spring为健康端点引入了缓存机制,默认情况下它缓存结果1秒。从文档:

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

一旦我改变了配置为:

endpoints: 
    health: 
    time-to-live: 0 

测试又开始传递。