Versions Compared

Key

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

...

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

Here the expected behaviour for our production code is captured within a Closure. (When using TDD, this closure would force the production code we saw in our original code to be created.)

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

Code Block
...
    def factory = [instance: myObjbusinessObj]
...

Here, myObj businessObj 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 (after some refactoring) the following complete test:

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

See also: Developer Testing using Closures instead of Mocks