在Spock中,您可以设置超时,此后测试将失败。
@Timeout(value = 1500, unit = TimeUnit.MILLISECONDS)
def "this method should not run longer than 2 seconds"() {
given:
userFilter = buildUserFilter(); // criteria to search users.
exportDestination = buildDestination(); // where to export users.
expect: "should not take long"
userService.exportUsers(userDetails);
}
现在我需要相反的事情:测试应该在超时后通过。
def "should block and wait until user-microservice is up"() {
given:
userExportMicroserviceClient = mock()
userExportMicroserviceClient.getUsers(_) >> httpNotFound
expect: "should block the current thread because userMicroservice is down"
failHere()
}
我知道,依靠其他服务可用性是一件坏事。这件事仅在数据迁移期间运行,与日常任务无关。
同样,我有一种方法可以为用户提供微服务,并在用户微服务启动之前一直阻塞。我该如何测试?
答案 0 :(得分:1)
这取决于您如何实现exportUsers()
方法。
假设它每秒拉动一个微服务。如果是这样,您可以依次模拟微服务的响应:向下,向下,向上。
// The timeout includes 2 seconds of microservice down.
@Timeout(value = 3500, unit = TimeUnit.MILLISECONDS)
def "should block and wait until user-microservice is up"() {
given: "mocked microservice which is not available for first 2 calls and available on 3rd call"
userExportMicroserviceClient = mock()
userExportMicroserviceClient.getUsers(_) >>> [httpNotFound, httpNotFound, httpOk]
when: "calling the user getting should take long time"
def actualResult = userService.exportUsers(userDetails)
then:
def expectedResult = <prepare>
actualResult == expectedResult
}
当然,这是一个伪代码,需要您针对项目进行更正。