18.6 Mocking Using Categories
In Section 13.1, Injecting Methods Using Categories, we discussed how categories provide controlled aspect-oriented programming (AOP) in Groovy. In this section we’ll see how we can use it to create mocks.
UnitTestingWithGroovy/TestUsingCategories.groovy | |
| import com.agiledeveloper.CodeWithHeavierDependencies |
| |
| class TestUsingCategories extends GroovyTestCase { |
| void testMyMethod() { |
| def testObj = new CodeWithHeavierDependencies() |
| |
| use(MockHelper) { |
| testObj.myMethod() |
| |
| assertEquals 35, MockHelper.result |
| } |
| } |
| } |
| |
| class MockHelper { |
| def static result |
| |
| def static println(self, text) { result = text } |
| |
| def static someAction(CodeWithHeavierDependencies self) { 25 } ... |
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.