问题
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