Mocking a Superclass in Spock

我怕爱的太早我们不能终老 提交于 2019-12-06 08:35:25

问题


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?


回答1:


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'



回答2:


The following code will help you to specify what methods are called actually.

setup:
def fooInstance = Spy(Foo)

when: "this try-catch block is debug code"
try {
  // do something with Foo or Bar
}
catch (Exception e) {
}

then:
0 * fooInstance._

This site may be useful. -> Spock Mock Cheatsheet



来源:https://stackoverflow.com/questions/24481973/mocking-a-superclass-in-spock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!