Skip to content

Instantly share code, notes, and snippets.

@gschueler
Last active August 29, 2015 13:57
Show Gist options
  • Save gschueler/9359884 to your computer and use it in GitHub Desktop.
Save gschueler/9359884 to your computer and use it in GitHub Desktop.
Exploring some Grails test mocks idioms
@TestFor(MyController)
public class MyTest{
@Test
public oldstyle(){
// use intermediate mock object which clutters the test
def svcMock=mockFor(MyService)
svcMock.demand.someMethod(1..1){input->null}
svcMock.demand.anotherMethod{auth,type,actions->
assert "project"== type
assert ['create']==actions
return true
}
//have to remember to assign to the service
controller.myService=svcMock.createMock()
}
@Test
public better(){
//make use of groovy's .with to skip the intermediate object
controller.myService=mockFor(MyService).with {
demand.someMethod(1..1){input->null}
demand.anotherMethod{auth,type,actions->
assert "something"== type
assert ['another']==actions
true
}
//unfortunately still need to call createMock() to return it
createMock()
}
}
/**
* or use a utility method like this, no need to call createMock() manually, and uses the mock.demand as the delegate
*/
private mockWith(Class clazz,Closure clos){
def mock = mockFor(clazz)
mock.demand.with(clos)
return mock.createMock()
}
@Test
public newstyle2(){
//easier way to demand methods
controller.myService=mockWith(MyService) {
someMethod(1..1){input->null}
anotherMethod{auth,type,actions->
assert "something"== type
assert ['another']==actions
true
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment