当前位置: 首页 > 知识库问答 >
问题:

Groovy spock测试关闭与间谍

李锦
2023-03-14

我有一个调用管道步骤方法(带有凭据)的共享库。我正在尝试测试withCredentials方法在调用myMethodToTest时是否被sh脚本正确调用,但在withCredentials闭包中迭代时遇到错误:

测试方法

 class myClass implements Serializable{
    def steps
    public myClass(steps) {this.steps = steps}

    public void myMethodToTest(script, credentialsId, dataObject) {
    dataObject.myKeyValue.each {
        steps.withCredentials([[
           $class: ‘UsernamePasswordMultiBinding’, credentialsId: "${credentialsId}",
           usernameVariable: 'USR', passwordVariable: 'PWD']]) {
             steps.sh("git push --set-upstream origin ${it.branch}")
           }
      }
   }      
}

嘲笑

class Steps {
   def withCredentials(List args, Closure closure) {}
}

class Script {
    public Map env = [:]
}

测试用例

def "testMyMethod"(){
        given:
        def steps = Spy(Steps)
        def script = Mock(Script)
        def myClassObj = new myClass(steps)
        def myDataObject = [
          'myKeyValue' : [['branch' :'mock' ]]
        ]

        when:
        def result = myClassObj.myMethodToTest(script, credId, myDataObject)

        then:
        1 * steps.withCredentials([[
            $class: 'UsernamePasswordMultiBinding', 
            credentialsId: "mycredId", 
            usernameVariable: 'USR', 
            passwordVariable: 'PWD'
        ]])  
        1 * steps.sh(shString)

        where:
        credId     | shString
        "mycredId" | "git push --set-upstream origin mock"

错误(it变量在闭包中变为null)

java.lang.NullPointerException: Cannot get property 'branch' on null object

共有2个答案

夏和雅
2023-03-14

请接受Leonard的回答,但我想发布一个带有少量修复的MCVE,这样其他人就可以实际运行测试并验证解决方案,因为即使有他的回答,你的代码也永远不会运行无误。我们开始吧(请注意我的评论):

package de.scrum_master.stackoverflow.q60044097

class Script {
  public Map env = [:]
}
package de.scrum_master.stackoverflow.q59442086

class Steps {
  def withCredentials(List args, Closure closure) {
    println "withCredentials: $args, " + closure
    // Evaluate closure so as to do something meaningful
    closure()
  }

  // Add missing method to avoid "too few invocations" in test
  def sh(String script) {
    println "sh: $script"
  }
}
package de.scrum_master.stackoverflow.q60044097

class MyClass implements Serializable {
  def steps

  MyClass(steps) { this.steps = steps }

  void myMethodToTest(script, credentialsId, dataObject) {
    // Fix wrong quotes in ‘UsernamePasswordMultiBinding’
    // and incorporate Leonard's solution to the nested closure problem
    dataObject.myKeyValue.each { conf ->
      steps.withCredentials(
        [
          [
            $class          : 'UsernamePasswordMultiBinding',
            credentialsId   : "${credentialsId}",
            usernameVariable: 'USR',
            passwordVariable: 'PWD'
          ]
        ]
      ) {
        steps.sh("git push --set-upstream origin ${conf.branch}")
      }
    }
  }
}
package de.scrum_master.stackoverflow.q60044097

import spock.lang.Specification

class MyClassTest extends Specification {
  def "testMyMethod"() {
    given:
    def steps = Spy(Steps)
    // Actually this noes not need to be a mock, given your sample code.
    // Maybe the real code is different.
    def script = Mock(Script)
    def myClassObj = new MyClass(steps)
    def myDataObject = [
      'myKeyValue': [['branch': 'mock']]
    ]

    when:
    // Result is never used, actually no need to assign anything
    def result = myClassObj.myMethodToTest(script, credId, myDataObject)

    then:
    1 * steps.withCredentials(
      [
        [
          $class          : 'UsernamePasswordMultiBinding',
          credentialsId   : "mycredId",
          usernameVariable: 'USR',
          passwordVariable: 'PWD'
        ]
      ],
      // Add missing closure parameter placeholder '_' to make the test run
      _
    )
    1 * steps.sh(shString)

    where:
    credId     | shString
    "mycredId" | "git push --set-upstream origin mock"
  }
}

请注意:让测试运行并让应用程序做一些有意义的事情只是为了完成这幅图。但实际上,您所问的问题是应用程序代码中的一个bug(以错误的方式使用嵌套闭包)。测试和应用程序代码中的其他错误只是隐藏了它,因为测试甚至从未到达有问题的部分。

更新:你的问题归结为以下两个可能的解决方案(B基本上是Leonard建议的):

def evalClosure(Closure closure) {
  closure()
}

// Problem: inner closure's 'it' shadowing outer closure's 'it'
[1, 2].each {
  println "outer closure: it = $it"
  evalClosure {
    println "inner closure: it = $it"
  }
}

println "-" * 30

// Fix A: make inner closure explicitly parameter-less
[1, 2].each {
  println "outer closure: it = $it"
  evalClosure { ->
    println "inner closure: it = $it"
  }
}

println "-" * 30

// Fix B: explicitly rename outer closure's parameter
[1, 2].each { number ->
  println "outer closure: number = $number"
  evalClosure {
    println "inner closure: it = $it"
    println "inner closure: number = $number"
  }
}

控制台日志:

outer closure: it = 1
inner closure: it = null
outer closure: it = 2
inner closure: it = null
------------------------------
outer closure: it = 1
inner closure: it = 1
outer closure: it = 2
inner closure: it = 2
------------------------------
outer closure: number = 1
inner closure: it = null
inner closure: number = 1
outer closure: number = 2
inner closure: it = null
inner closure: number = 2
邢华清
2023-03-14

您有两个嵌套闭包的情况

dataObject.myKeyValue.each { // <- first closure it references the map
    steps.withCredentials([[
       $class: ‘UsernamePasswordMultiBinding’, credentialsId: "${credentialsId}",
       usernameVariable: 'USR', passwordVariable: 'PWD']]) { // <- second closure it is null as no parameter is passed to this closure
         steps.sh("git push --set-upstream origin ${it.branch}")
    }
}

要修复它,您应该命名第一个参数

dataObject.myKeyValue.each { conf ->
    steps.withCredentials([[
       $class: ‘UsernamePasswordMultiBinding’, credentialsId: "${credentialsId}",
       usernameVariable: 'USR', passwordVariable: 'PWD']]) {
         steps.sh("git push --set-upstream origin ${conf.branch}")
    }
}
 类似资料:
  • ATDD的基本周期是在我们写验收测试之后,我们写那个验收测试的TDD测试。但我的问题是,您如何指定哪个单元测试与哪个验收测试相关?通过我们在ATDD和TDD上所做的特性或其他技术,这是可能的吗?

  • 我正在Ruby中运行WebDriver测试,我在关闭Internet Explorer浏览器时遇到了一个问题:当我想关闭浏览器的窗口时,IE弹出提示“您确定要离开此页吗”,并且有两个选项“离开此页”和“留在此页”。 我尝试了几种关闭浏览器的方法,但都没有成功: 我很感激你能提供的任何帮助

  • 下面是我编写测试的方法: 具有私有方法和运行所有其他私有方法的单个公共方法的类。 我在其他类中有一些通用方法,其中一个名为navigation.php。在这个类中,我有所有的方法,这些方法使我能够进入应用程序的特定点。 我所要做的就是,根据一个条件,正确地关闭(或退出,或处置,或任何你想要的)我的测试,而不返回一个错误。我尝试了quit()、close()和dispose(),但可能我用错了。

  • 想改进这个问题吗 通过编辑此帖子,添加详细信息并澄清问题。 我在“联系人”类中有一个静态类“电子邮件”。在测试中,我有一个例外: 这是测试中的代码: 电子邮件1和联系人。电子邮件是电子邮件类的对象,不是吗?

  • 想要改进这个问题吗?更新问题,以便通过编辑这篇文章用事实和引用来回答。 最初的关闭原因未得到解决 我正在尝试了解PACT和Spring Cloud合同之间更好的工具来实施消费者驱动程序合同测试。我没有找到任何明确的例子来找到优缺点。 我想实现CDCT,我在项目中不使用Spring。根据我的理解,我认为PACT是很好的选择。 欢迎任何信息或建议。谢谢你。