[英]How do I write multiple unit tests using Spock framework?
該測試的目標是獲取一個整數數組,找到最大值,並計算該最大值的頻率。 我將如何更改此代碼以進行多次測試。 另外,我想知道這是否是測試此問題的正確方法。
我是TDD的新手,目前正在練習針對易於解決的練習題編寫測試。
謝謝!
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
}
}
您可以添加帶值表的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
}
並添加行以添加測試變體。
正如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”)
注意where塊中的as int[]
。 替代方法是def candles = new BirthdayCandles(testInput as int [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.