首页 > 解决方案 > 数据驱动的 Spock 测试

问题描述

我正在做一些非常基本的 Spock 复习练习,并且正在尝试进行数据驱动测试。这是规格:

package drills

import drills.StringReverse
import spock.lang.Specification

import org.junit.Test

class TestSpockReverseString extends Specification {

    @Test
    def "test"(String inString, String expectedString){

        given:

        StringReverse systemUnderTest = new StringReverse();

        when:
        String actualString = systemUnderTest.reverseString(inString);

        then:
        expectedString.equals(actualString)

        where:
        inString    | expectedString
        null        | null
        ""          | ""
        "abc"       | "cba"
        "aaa"       | "aaa"
        "abcd"      | "dcba"
        "asa"       | "asa"
    }
}

每次我运行它时,我都会收到此错误:

错误信息

我已经浏览了 Spock 文档并在线阅读了其他示例,看起来我正确设置了规范。我正在为 EE Java 运行 Eclipse IDE。版本 2020-03 (4.15.0)

我需要更新一些设置以使 Groovy 和 Spock 正常工作?

任何想法,将不胜感激。

更新:我尝试使用此处的规范之一:

https://github.com/spockframework/spock-example/blob/master/src/test/groovy/DataDrivenSpec.groovy

即这个:

def "minimum of #a and #b is #c"() {
  expect:
  Math.min(a, b) == c

  where:
  a | b || c
  3 | 7 || 3
  5 | 4 || 4
  9 | 9 || 9
}

与上述相同的问题。我认为我的 Eclipse 设置有问题。我已经查看了 groovy 编译器、测试运行程序,但不知道还能去哪里看。同样,任何想法都将不胜感激。谢谢。

标签: spockdata-driven-tests

解决方案


你想摆脱@TestSpock 测试中的 JUnit 注释,那么它可以在有或没有特性方法参数的情况下工作。这是您的规范的一个不那么冗长和更“怪异”的版本:

package de.scrum_master.stackoverflow.q63959033

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

class TestSpockReverseString extends Specification {
  @Unroll
  def "reversing '#inString' yields '#expectedString'"() {
    expect:
    expectedString == new StringReverse().reverseString(inString)

    where:
    inString | expectedString
    null     | null
    ""       | ""
    "abc"    | "cba"
    "aaa"    | "aaa"
    "abcd"   | "dcba"
    "asa"    | "asa"
  }

  static class StringReverse {
    String reverseString(String string) {
      string?.reverse()
    }
  }
}

顺便说一句,@Unroll将是 Spock 2.0 中的默认设置,您只需要在 1.x 版本中使用它。


推荐阅读