为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Spock 框架编写多个单元测试?

如何使用 Spock 框架编写多个单元测试?

繁华开满天机 2021-12-10 16:56:56
这个测试的目标是取一个整数数组,找到最大值,并计算该最大值出现的频率。我将如何更改此代码以进行多次测试。另外,我想知道这是否是测试此问题的正确方法。我是 TDD 的新手,目前正在练习编写测试以解决易于解决的练习问题。谢谢!import spock.lang.Specificationclass BirthdayCandlesTest extends Specification {    def "GetNumberOfMaxHeightCandles"() {        given: "A BirthdayCandles object"        int[] test = [1,1,1,3,3,3,3]        def candles = new BirthdayCandles(test)        when: "I call the max number height method"        def result = candles.getNumberOfMaxHeightCandles()        then: "I should get the frequency count of the max number in the integer array"        result == 4    }}
查看完整描述

2 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

正如 John Camerin 所说,您可能正在寻找spock 中的数据驱动测试。


我会提供一个稍微不同的答案:


def "GetNumberOfMaxHeightCandles"() {

    given: "A BirthdayCandles object"

    def candles = new BirthdayCandles(testInput)


    when: "I call the max number height method"

    def actual = candles.getNumberOfMaxHeightCandles()


    then: "I should get the frequency count of the max number in the integer array"

    actual == expectedResult


    where:

    testInput                  |     expectedResult

    [1,1,1,3,3,3,3]  as int [] |     4

    [1,1,1,3,3,3,4]  as int [] |     1

}

几个观察:


请注意,我没有在这里使用字符串插值(没有“$result”和“$test”)


请注意as int[]where 块中的 。它的替代方案是def candles = new BirthdayCandles(testInput as int [])


查看完整回答
反对 回复 2021-12-10
?
潇湘沐

TA贡献1816条经验 获得超6个赞

您可以添加一个 where: 块,其中包含一个值表,其中第一行是变量名,可以在测试的其余部分使用。例如


def "GetNumberOfMaxHeightCandles"() {

        given: "A BirthdayCandles object"

        def candles = new BirthdayCandles("$test")


        when: "I call the max number height method"

        def result = candles.getNumberOfMaxHeightCandles()


        then: "I should get the frequency count of the max number in the integer array"

        result == "$result"


        where:

        test             |     result

        [1,1,1,3,3,3,3]  |     4

        [1,1,1,3,3,3,4]  |     1

}

只需添加行即可添加测试变体。


查看完整回答
反对 回复 2021-12-10
  • 2 回答
  • 0 关注
  • 137 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信