Can';无法在与spock的继承关系中创建模拟

Can';无法在与spock的继承关系中创建模拟,spock,Spock,我是斯波克的新手。我在普通类中创建了mock对象,效果很好。但是当我们有如下类似于继承的结构时,我就不能正确地模拟它给出的错误(空指针)。任何人都知道我们如何在斯波克做到这一点 Class Parent{ Third getThird(){ return third; } } Class Child extend Parent{ Object method1(){ String msg=getThird().someMethod(); /

我是斯波克的新手。我在普通类中创建了mock对象,效果很好。但是当我们有如下类似于继承的结构时,我就不能正确地模拟它给出的错误(空指针)。任何人都知道我们如何在斯波克做到这一点

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
你能试试这个吗

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

您可以像任何接口一样在Spock中模拟类:

given:
    def thirdMock = Mock(Third) {
      someMethod() >> "xyz"
    }
    def child = Mock(Child) {
      third >> thirdMock
    }
when :
  def object = child.method1()
then:
  //comparing the things
然而,这通常是代码不可测试的症状。在您的情况下,您可能应该使“第三个”可注射,然后注射一个mock