Grails unit test verify mock method called

不羁岁月 提交于 2020-01-15 05:45:51

问题


In my unit test, I mock a service (which is a ref of the class under test).

Like:

given:
def mockXxService = mockFor(XxService)
mockXxService.demand.xxx(1) {->}
service.xxService = mockXxService
when:
service.yyy()
then:
// verify mockXxService's xxx method is invoked.

For my unit test, I want to verify that mockXxService.xxx() is called. But grails document's mockControl.verify() doesn't work for me. Not sure how to use it correctly.

It is very similar to mockito's verify method.

Anyone knows it?


回答1:


You are using spock for your unit test, you should be easily able to use spock's MockingApi check invocations:

given:
    def mockXxService = Mock(XxService)
    service.xxService = mockXxService
when:
    service.yyy()
then:
    1 * mockXxService.xxx(_) //assert xxx() is called once

You could get more insight about mocking from spockframework docs.

You can even stub and mock that while mocking the concerned service as:

def mockXxService = Mock(XxService) {
    1 * xxx(_)
}



回答2:


If you want Mockito-like behavior in Grails unit tests - just use Mockito. It is far more convenient than Grails' mocking methods.



来源:https://stackoverflow.com/questions/21520212/grails-unit-test-verify-mock-method-called

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