Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

We might be tempted to replace logger and factory with Groovy's built-in mocks, but it turns out that Maps or Expandos are often sufficiently powerful enough in Groovy that we don't need full blown dynamic mocks for this example.

Instead of a mock for logger, we can use an Expando as follows:

Code Block
...
    def logger = new Expando()
    logger.log = { msg -> assert msg == 'Something done with: ' + param }
...

Insread Instead of a mock for factory, we can use a simple map as follows:

...

Here, myObj is the object we want the factory to return, though in general this could be a Closure similar to what we did for the Expando above.

Putting this altogether yields te the following complete test:

Code Block
class MyAppTest extends GroovyTestCase {
    void testDoesBusinessLogic() {
        // triangulate
        checkDoesBusinessLogic "case1"
        checkDoesBusinessLogic "case2"
    }
    private checkDoesBusinessLogic(param) {
        def logger = new Expando()
        logger.log = { msg -> assert msg == 'Something done with: ' + param }
        def myMeth = { assert it == param }
        def myObj = new Expando()
        myObj.doSomething = { assert it == param }
        myObj.doSomethingElse = { assert it == param }
        def factory = [instance: myObj]
        def cut = new MyApp(logger:logger, factory:factory)
        cut.doMyLogic(param)
    }
}

...