Writing a parameterized test method in spock

时间:2017-12-18 06:23:13

标签: testing groovy spock

I'm writing a test in Spock and currently, this is the base structure:

def "someTest"(String str, Class<? extends SomeClass> clazz) {

    setup:
       (current implementation)
       obj.get("Sample1")
       obj.get("Sample2")
       obj.get("Sample3")
       ... so on

       (what I want to implement)
       object.get(str)

    when:
    ...

    then:
    ...
}

I need to use str and clazz in setup:, when: and then: and so I need a way to call the method multiple times.

I've already read some tuts online: https://www.testwithspring.com/lesson/writing-parameterized-tests-with-spock-framework/ but really have no idea on how to implement it with non-primitive types

1 个答案:

答案 0 :(得分:0)

在spock中,您可以在where:部分中提供参数化测试的值,作为Ascii&#39;表格&#39;或列表。 Spock使用AST转换将这样的表转换为单独的方法调用。所以看起来很神奇。

  @Unroll // formats method name. Can be on class level
  def "Name of #clazz is not #str"(String str, Class clazz) {
    setup:
    // TODO: real setup
    str == clazz.name

    // TODO: when/ then only useful for stimulus-response tests
    when:
    str == clazz.name

    then:
    str == clazz.name

    // TODO: expect not needed when using when/then
    expect:
    str == clazz.name

    where:
    str                  | clazz
    "java.lang.String"   | String.class
    "java.lang.Integer"  | Integer.class

  }

这可能看起来不像,但该方法会在&#39;表格中的每一行运行多次。值,您可以使用无效值检查并使每个方法调用失败。