我是spock的新手。我在普通类中创建了模拟对象,它的工作正常。但是当我们像下面的结构那样继承时,我就无法正确地模拟它给出的错误(空指针)。任何人都知道如何在spock中做到这一点。
Class Parent{
Third getThird(){
return third;
}
}
Class Child extend Parent{
Object method1(){
String msg=getThird().someMethod(); // need to mock this line
return object;
}
}
given:
Third third=Mock()
Child child=new Child()
child.getThird(false) >> third
third.someMethod() >> "xyz"
when :
Object object=child.method1()
then:
//comparing the things
答案 0 :(得分:0)
你能试试吗?:
given:
def third = Mock(Third)
Child.metaClass.getThird = {
third
}
when :
Object object=child.method1()
then:
1 * thirdMocked.someMethod() >> "xyz"
and:
//comparing the things
cleanup:
Child.metaClass = null
答案 1 :(得分:0)
你可以像任何接口一样在Spock中模拟类:
given:
def thirdMock = Mock(Third) {
someMethod() >> "xyz"
}
def child = Mock(Child) {
third >> thirdMock
}
when :
def object = child.method1()
then:
//comparing the things
然而,它通常是代码不能真正测试的症状。在你的情况下,你应该做第三个'注射,然后注入模拟。