如何使用 Spock 模拟 class 中变量的值

How to mock the value of variable inside a class using Spock

测试Class

Class TestClass{

    @Autowired
    AnyClass anyClass

    boolean testMethod() {
        boolean result = anyClass.method()
        if(result) {
            return !result
        }
        else {
            return !result
        }
    }
}

我的斯波克

class TestClassSpec implements Specification {

    AnyClass anyClass = Mock()
    TestClass testClass = new TestClass(anyClass: anyClass)

    def "check if opposite of result is returned"()  { 
        given: 
        anyClass.method >> {return true}

        when:
        boolean result = testClass.testMethod()

        then:
        result == false
    }
}

当我尝试调试时,结果变量始终为空。无论如何我可以在不改变原始测试的情况下将值注入结果变量class?

如评论中所述,您的代码不太合适,但我建议您以这种方式注入变量:

  def "check if opposite of result is returned"() {
    when:
    boolean result = testClass.testMethod()

    then:
    anyClass.method() >> false

    and:
    result == false
  }

您的代码有几个问题:

  1. 你需要 extend Specification 而不是 implement
  2. 如果您存根一个方法,您需要包含 (),例如, anyClass.method >> {return true} 会尝试模拟 属性,正确的调用是 anyClass.method() >> true 这是 主要问题
  3. 如果你只想return一个固定值
  4. { return true }是多余的
  5. if-else 完全多余
interface AnyClass {
    boolean method()
}

class TestClass{

    AnyClass anyClass

    boolean testMethod() {
        boolean result = anyClass.method()
        return !result        
    }
}

class TestClassSpec extends spock.lang.Specification {

    AnyClass anyClass = Mock()
    TestClass testClass = new TestClass(anyClass: anyClass)

    def "check if opposite of result is returned"()  { 
        given: 
        anyClass.method() >> true

        when:
        boolean result = testClass.testMethod()

        then:
        result == false
    }
}

Groovy Console

中测试