Verify Spock mock with specified timeout

心已入冬 提交于 2019-12-01 04:42:05
th3morg

I was trying to use PollingConditions to satisfy a similar scenario (which wasn't helpful), but instead found satisfaction in Spock's BlockingVariables. To verify that SomeService.method() is invoked at least once in function ClassBeingTested.method() within a given timeout period:

def "verify an interaction happened at least once within 200ms"(){
    given:
        def result = new BlockingVariable<Boolean>(0.2) // 200ms
        SomeService someServiceMock = Mock()
        someServiceMock.method() >> {
            result.set(true)
        }
        ClassBeingTested clazz = new ClassBeingTested(someService: someServiceMock)
    when:
        clazz.someMethod()
    then:
        result.get()
}

When the result is set, the blocking condition will be satisfied and result.get() would have to return true for the condition to pass. If it fails to be set within 200ms, the test will fail with a timeout exception.

There is no equivalent in Spock. (PollingConditions can only be used for conditions, not for interactions.) The closest you can get is to add a sleep() statement in the then block:

when:
...

then:
sleep(200)
(1.._) * mock.baz()

Using PollingConditions and a boolean variable, the following example evaluates a function until it satisfies an interaction.

def "test the config watcher to reload games if a new customer directory is added"() {

given:
def conditions = new PollingConditions(initialDelay: 1, timeout: 60, factor: 1.25)
def mockGameConfigLoader = Mock(GameConfigLoader)
def gameConfigWatcher= new GameConfigWatcher(mockGameConfigLoader)
boolean gamesReloaded = false

when:
conditions.eventually {
    gameConfigWatcher.listenEvents()
    assert gamesReloaded
}

then:
1 * mockGameConfigLoader.loadAllGameConfigs() >> {
    gamesReloaded = true
}
0 * _

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!