1

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 ?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Thermech
  • 4,371
  • 2
  • 39
  • 60

2 Answers2

3

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

class MyTest {
  int someMethodCount

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

}
  • I wonder how come we look at the same problem in the same time and moreover on a long weekend for me, Memorial Day... :). BTW your approach is a good way in case of strict mocking. – dmahapatro May 25 '13 at 16:31
  • @dmahapatro It was a quick look in SO during lunch time (here in Brazil) :-) –  May 25 '13 at 23:02
0

If you do not care about strict mocking and are only unit testing someMethod then you can use the primitive methodology of using maps:

void testSomething() {
    def mockUtil = ["someMethod" : {param->
        //I have used param only to handle conditional logics
        //param can be optional
        if(param == 1)return "John"
        if(param == 2)return "Nancy"
        if(param == 3)return "Mark"
    }]

    assert mockUtil.someMethod(1) == "John"
    assert mockUtil.someMethod(2) == "Nancy"
    assert mockUtil.someMethod(3) == "Mark"
}
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • where is mockUtil defined ? in above code you have , you don't seem to show where mockUtil is defined , you are just setting it. – grepit Oct 06 '14 at 15:06
  • My bad. I am trying to just showcase how loose mocking can be done. See my update. Although the test case is dumb, the idea is to use a map with string key (matching method name) and a closure as value. Thanks for pointing that out after more than a year. :) @CPU100 – dmahapatro Oct 06 '14 at 15:14