Search code examples
unit-testinggrailsmockingspock

Mocking a Superclass in Spock


How can you unit test a class that has a superclass in Spock that invokes method calls form its superclass? Or how do you mock a superclass in Spock?

Ex:

class Bar {

  def method1(parm1){
      //Method actions
  }
}


class Foo extends Bar {

   def method2(param1, param2) {          
       //Method actions
       super.method1(param1)
   }
}

How can I mock behavior of class Bar?


Solution

  • You might use your class Foo as a Spy. The spy will create an instance of your class Foo but gives you the possibility of mocking any public methods declared in your spies class hierarchy.

    def fooInstance = Spy(Foo)
    fooInstance.method1(_) >> 'return value'