12.1.6 Mocking Collaborators - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 2.3.8
12.1.6 Mocking Collaborators
Beyond the specific targeted mocking APIs there is also an all-purposemockFor()
method that is available when using the TestFor
annotation. The signature of mockFor
is:mockFor(class, loose = false)
def strictControl = mockFor(MyService) strictControl.demand.someMethod(0..2) { String arg1, int arg2 -> … } strictControl.demand.static.aStaticMethod {-> … }
mockControl.createMock()
to get an actual mock instance of the class that you are mocking. You can call this multiple times to create as many mock instances as you need. And once you have executed the test method, call mockControl.verify()
to check that the expected methods were called.Grails mocks also provide a demandExplicit
method that can be used in place of demand. This will check the mocked class's metaClass and throw an ExplicitDemandException if a method with that name and signature doesn't exist. For example, given the service:class MyService {
def someMethod(String s) { … }
}
def strictControl = mockFor(MyService)
//Works just like the demand method since method signature exists on the class
strictControl.demandExplicit.someMethod(1) { String arg1 }
def strictControl = mockFor(MyService) //Throws ExplicitDemandException because method signature doesn't exist strictControl.demandExplicit.someMethod(1) { String arg1, String arg2 }
def looseControl = mockFor(MyService, true)