Search code examples
grailsmockinggrails-2.2

Grails mock same method many times with different result


I want to mock a object method that is called many times, and each times the result must be different.

Here what I'm trying to do:

fooMock.demand.someMethod(3..3) { ->
    //call1
    if (**some condition**)
        return 1

    //call2
    if (**some condition**)
        return 2

    //call3
    if (**some condition**)
        return 3
}

So, is there a way to know what is the current call number ? or do you offers something better ?

It will be possible to do that in Grails 2.3-M2 (http://jira.grails.org/browse/GRAILS-4611) but until then, did someone has a workaround ?


Solution

  • You can create an attribute in your test to control that:

    class MyTest {
      int someMethodCount
    
      @Before
      void setup() {
        fooMock.demand.someMethod(3..3) { ->
          someMethodCount++
          ...
        }
      }
    
    }