简体   繁体   English

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

[英]How do I write multiple unit tests using Spock framework?

The goal of this test is to take an integer array, find the max value, and count the frequency of that max value. 该测试的目标是获取一个整数数组,找到最大值,并计算该最大值的频率。 How would I change this code to test multiple times. 我将如何更改此代码以进行多次测试。 Also, I'd like to know if this is the correct approach to testing this problem. 另外,我想知道这是否是测试此问题的正确方法。

I'm new to TDD and I'm currently practicing writing tests for easily solvable practice problems. 我是TDD的新手,目前正在练习针对易于解决的练习题编写测试。

Thanks! 谢谢!

import spock.lang.Specification

class 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
    }
}

You can add a where: block with a table of values with the first row being the variable names which can be used in the rest of the test. 您可以添加带值表的where:块,其中第一行是变量名称,可以在其余测试中使用。 For example 例如

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
}

and just add rows to add test variations. 并添加行以添加测试变体。

As John Camerin stated you're probably looking for Data Driven Testing in spock. 正如John Camerin所说,您可能正在寻找spock中的数据驱动测试

I'll provide a slightly different answer: 我将提供一个略有不同的答案:

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
}

A couple of observations: 一些观察:

  • Note that I didn't use string interpolation here (no "$result" and "$test") 请注意,我没有在这里使用字符串插值(没有“ $ result”和“ $ test”)

  • Note the as int[] in the where block. 注意where块中的as int[] An alternative to it would be def candles = new BirthdayCandles(testInput as int []) 替代方法是def candles = new BirthdayCandles(testInput as int [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM