Last active
August 29, 2015 13:57
-
-
Save gschueler/9359884 to your computer and use it in GitHub Desktop.
Exploring some Grails test mocks idioms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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