unit-testing - 在 : block in Spock test 中传递一个值

标签 unit-testing groovy spock

是否可以像这样在 where 块中传递一个值。

我试过这个。但它失败并给出 MissingPropertyException。

我希望 name1 和 name2 位于方法内部。

def "length of names #name"()  {    
        def name1 = "Spock"
        def name2 = "Java"

        expect:
            name.size() == length

        where:
            name        || length
            name1       || 5
            name2       || 2
    }

最佳答案

测试数据属于 where 块,在测试(特征)方法中没有硬编码。
看到这一点的一种粗略方法是将测试主体(不包括 where 块)视为具有一定数量参数的方法 - 在您的情况下为 2,名称和长度。然后意识到 where 子句只是向测试运行程序提供数据值,以便在调用您的测试方法时使用。
Spock 使用 Groovy 魔法进行转换

def "test length of names"()  {
    expect:
        name.size() == length   
    where:
        name     | length
        "Spock"  | 5
        "Java"   | 4
}
大致像
def test_length_of_names(name, length)  { // note the arguments
    assert name.size() == length
}
然后告诉测试运行程序为 where 子句中的每一行调用一次测试
test_length_of_names("Spock", 5)
test_length_of_names("Java", 4)
这种方法
  • 在测试逻辑和测试数据之间提供了很好的关注点分离
  • 允许将相对通用的测试重用于各种输入和边缘情况
  • 避免重复测试代码
  • 支持一种名副其实的数据驱动测试的测试设计风格。

  • 此解释遗漏了一些细节,例如为每个测试创建规范的实例、更新每个测试调用的名称以及调用各种设置和清理方法。
    the Spock documentation更多细节。

    关于unit-testing - 在 : block in Spock test 中传递一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19015236/

    相关文章:

    javascript - 如何检查与显示相关的文本内容 :none style

    groovy - Groovy 编译器是否能够生成有关已弃用代码的警告?

    java - Groovy 2.5.0 为方法调用转换提供 noclassdefounderror

    unit-testing - Grails 2.4.4中带有@TestFor的ClassCastException

    java - spock - 模拟静态方法不起作用

    ruby-on-rails - Controller 测试错误消息 : "ActionView::Template::Error: The asset "MyString"is not present in the asset pipeline"

    unit-testing - 使用 Jasmine 测试时,如何触发 $emit 来测试 Controller 中的 $on 监听器?

    grails - 如何使用grails 3.3.9在RestBuilder的post请求中发送 header

    unit-testing - 如何在VS2013中自动运行单元测试

    java - Groovy 和 Java 静态变量行为