在Spock测试中运行时出现MissingPropertyException异常

3

我有以下用groovy编写的测试(使用spock框架):

def "#checkPassword check if passwd match"() {
    given:
    def allowedPasswords = ["1", "2"]

    expect:
    myStrategy.checkPassword(myModel, input) == result

    where:
    input | result
    allowedPasswords   | true
}

然而,当我运行它时,allowedPasswords 字段似乎丢失了。我收到了以下错误提示:
groovy.lang.MissingPropertyException: No such property: allowedPasswords for class: 

我不知道为什么,因为我已经在“given”部分声明了它。你能帮我解决这个问题吗?


你对它有什么期望? - tim_yates
我期望它运行checkPassword方法,并将allowedPassword作为其中一个参数之一。 - randomuser1
2个回答

3

看起来你正在寻找@Shared

import spock.lang.Shared
import spock.lang.Specification

class SpockTest extends Specification {
    @Shared allowedPasswords = ["1", "2"]

    def "#checkPassword check if passwd match"() {
        expect:
        checkPassword(input) == result

        where:
        input << allowedPasswords
        result << allowedPasswords
    }

    static String checkPassword(String input) {
        return input
    }
}

2
你的问题出在where:块逻辑上属于测试夹具 - 请记住,在@Unroll情况下,“where”变量值甚至会编译成方法名称!请参见下面的示例代码。也就是说,在given:块之前评估where:,因此您不能指望它在测试期间了解稍后初始化的局部变量。
至于你测试代码的其余部分:如果没有重用allowedPasswords,我建议你将其内联。你已经接受的答案或者我要向你展示的替代方案仅在你重用所涉及的变量并且不想两次内联它以使测试维护更容易时使用。当然,如果重用,则Dmitry的答案是正确的。但是,它会使测试代码有点难以阅读和理解。我建议你追求可读性,因为良好的BDD测试是应用程序行为的规范,因此Spock测试基类名称为Specification,而Geb基类名称为GebSpec
现在关于Dmitry的答案,我只想表明您可以使用老式的static作为@Shared的替代方案,并提供一些重用的示例代码,这样更有意义,也更接近您自己的测试用例。我希望您以任何方式接受我的答案,而是他在我之前正确回答了问题,我只是在这里分享额外的细节。在他的答案中,我只是缺少解释为什么您的代码不起作用的解释,所以我感到有必要回答。 :-)
package de.scrum_master.stackoverflow

import spock.lang.Specification
import spock.lang.Unroll

class AllowedPasswordsTest extends Specification {
  static allowedPasswords = ["1", "2"]

  @Unroll
  def "password check for '#input' should return #result"() {
    expect:
    checkPassword(input) == result

    where:
    input << allowedPasswords + ["3", "oops", "  ", null]
    result = input in allowedPasswords
  }

  static boolean checkPassword(String input) {
    return input?.trim()?.matches("[12]")
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接