问题
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