有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spock框架中的java高级助手方法

我使用斯波克框架。我知道一些助手方法可以封装来自then:块的逻辑。我需要的是在同一个类中的不同特性方法之间重用几行代码。这些代码行包含when:then:块,例如:

def "myFeatureMethod"() {
    given:
    ...

    when:
    ...

    then:
    ...

    myHelperMethod
}

private void myHelperMethod() {
    when:
    ...

    then:
    ...
}

据我所知,斯波克目前不可能做到这一点。有没有什么解决方法可以达到同样的效果


共 (1) 个答案

  1. # 1 楼答案

    Spock现在确实允许then:块中的助手方法——从documentation

    def "offered PC matches preferred configuration"() {
      when:
      def pc = shop.buyPc()
    
      then:
      matchesPreferredConfiguration(pc)
    }
    
    def matchesPreferredConfiguration(pc) {
      pc.vendor == "Sunny"
      && pc.clockRate >= 2333
      && pc.ram >= 4096
      && pc.os == "Linux"
    }
    

    或者有更好的错误信息:

    void matchesPreferredConfiguration(pc) {
      assert pc.vendor == "Sunny"
      assert pc.clockRate >= 2333
      assert pc.ram >= 4096
      assert pc.os == "Linux"
    }