Tuesday 8 July 2008

Ooops Mocks

Why do this ...
void testOne() {
def result
mockServiceA.use {
mockServiceB.use {
mockServiceC.use {
result = testMe.someMethod('a', 'b')
}
}
}
assertEquals(1, result)
}

void testTwo() {
def result
mockServiceA.use {
mockServiceB.use {
mockServiceC.use {
result = testMe.someOtherMethod('a', 'b')
}
}
}
assertEquals(1, result)
}


When you can do this...

void testOne() {
def result = executeWithMocks { testMe.someMethod('a', 'b') }
assertEquals(1, result)
}

void testTwo() {
def result = executeWithMocks { testMe.someOtherMethod('a', 'b') }
assertEquals(1, result)
}

private Object executeWithMocks(Closure closure) {
def result
mockServiceA.use {
mockServiceB.use {
mockServiceC.use {
result = closure()
}
}
}
return result
}

No comments: