Mock multiple calls to the same method in spock
Asked Answered
S

1

14

I am currently writing unit testcase for a groovy application

class Page{
   ..
   ..
   str1 = obj.getDateBasedOnValue("A");
   str2 = obj.getDateBasedOnValue("B");
}

Test class

class PageSpec extends Specification{
   Obj obj = Mock(Obj)
   ...
   def "testCase 1"(){
      obj.getDateBasedOnValue(_) >> "some date string 1"
      obj.getDateBasedOnValue(_) >> "some date string 2"
   }
}

Can someone tell me if this is the right way to mock both the calls in spock? If no then please guide me towards the right solution.

Semicolon answered 13/11, 2020 at 7:53 Comment(0)
D
21

To return different values on successive invocations, use the triple-right-shift (>>>) operator:

def "testCase 1"(){
    obj.getDateBasedOnValue(_) >>> ["some date string 1", "some date string 2"]
}

Then getDateBasedOnValue() will return "some date string 1" for the first time and "some date string 2" for the second time.

Dessertspoon answered 13/11, 2020 at 8:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.