前言
spock.genesis.Gen有几个数字生成器。所有基于基本数字类型都有一个直接的方法来生成随机值,而且不建立任何限制。
一、无约束自动生成
def 'generate numbers'() {
expect:
Gen.getDouble().iterator().next() instanceof Double
println(Gen.getDouble().iterator().next())
Gen.integer.iterator().next() instanceof Integer
println(Gen.integer.iterator().next())
Gen.getLong().iterator().next() instanceof Long
println(Gen.getLong().iterator().next())
Gen.bytes.iterator().next() instanceof byte[]
println(Gen.bytes.iterator().next())
}
运行结果:
0.6599904847978021
107182731
9191082748347817671
[26, -128, 95, -14, 51, -20, 14, 105, -5, 122, -107, 59, 53, 102, -117, 43, -53, 5, -20, -58, 83, 14, -60, 75, 84, 64, -11, 66, -47, 73, -71, -102, 12, 15, 29, 53, 96, -112, -11, -71, -75, 46, -63, 66, -89, 125, 48, 62, -23, -111, -15, 29, 15, -79, -52, -29, 51, 41, 122, -80, 69, 83, 2, 58, -87, 10, -109, -101, 62, -8, 50, -60, 27, 124, -24, -48, -45, -91, -79, 101, 85, 59, -23, 47, 37, 90, 123, -71, 17, -110, -80, 57, 103, 82, 114, 72, 123, -33, 43, -9, -54, -39, -99, -91, 124, 87, -101, 121, -105, 97, 119, 33, 47, 88, -11, 22, -70, 94, 102, 11, 33, -16, 118, -77, 79, -74, 1, 104, 82, -108, 5, 121, -11, -79, -50, -58, 14, -93, -102, -66, -27, 85, -86, 87, 22, -71, 20, 14, 41, -42, -58, -107, -71, 32, 99, -53, 106, -99, -128, -127, -63, 78, 9, -67, 35, 47, 46, -37, 103, -121, -86, 55, 66, -8, 69, -37, -80, -11, -35, 45, -126, 44, -13, -70, -46, -55, -111, 113, -9, -21, -107, 24, -98, -25, -66, 121, -83, 107, 118, -69, 5, 92, 39, -92, 73, -115, 98, 7, 38, -55, -89]
二、可约束生成Integer
对于整数Integer,还有一些方法可以直接设置生成值的边界。一是使用groovy的范围进行约束。二是通过传递最大值和最小值两个参数约束。
def 'create an integer with min and max'() {
when: 'establishing max possible number'
def firstNumber = Gen.integer(5..10).iterator().next()
then: 'generated number will be less equals than max'
firstNumber >= 5
firstNumber <= 10
println(firstNumber)
when: 'establishing min and max valid numbers'
def secondNumber = Gen.integer(5,10).iterator().next()
then: 'generated number must be between both numbers'
secondNumber >= 5
secondNumber <= 10
println(secondNumber)
}
运行结果:
8
7
``
总结
整数Integer的约束生成类似遇string的约束生成。bytes的自动生成为一个数组与其他生成值不一致