Search code examples
unit-testinggrailsgroovymockitospock

Grails Unit testing - mock findAllBy() method with each closure


I want to Unit test a function in a service class.

The service class looks like this:

    class FooService{ 

    Double getFoo(SomeClass class){
      Double returningValue = 0.0
      String parameter

      SomeClass.findAllByCodeLike(parameter).each{
        Double amount = someOtherFooServiceMethod(it,it.someClassAttribute?.intValue())
        if(amount){
         returningValue += amount;
         }
       }
     }

    }



I know how to mock the SomeClass.findAllByCodeLike(parameter). I mocked it with the SomeClass.metaClass.static.findAllByCodeLike() and assign to this function a value.

But i don't know how to mock the .each{}. Is there way to do it?

By now I'm mocking a lot of domain classes to test this method and also save the domain classes into the in memory database. If i find a way to mock SomeClass.findAllByCodeLike(parameter).each{...} i can reduce the TestClass by a lot of code.


Solution

  • You don't have to mock the each{}. You shoud simply make your findAllByCodeLike mock return a list of values:

    SomeClass.metaClass.static.findAllByCodeLike = { code -> [ new SomeClass(...), new SomeClass(...), ... ] }
    //...
    SomeClass.findAllByCodeLike(parameter).each{ 
      doStuff it
    }