【发布时间】:2020-08-11 09:46:18
【问题描述】:
对于 Spock,假设某些函数会在某些条件下返回意外结果,如何匹配部分结果而忽略其他结果?
int[] randomOnCondition(int input) {
def output = input == 1 ? Random.newInstance().nextInt() : input
[input, output]
}
def test() {
expect:
randomOnCondition(input) == output as int[]
where:
input || output
2 || [2, 2]
1 || [1, _] //how to match part of the result and ignore others?
}
更新
def test() {
expect:
Integer[] output = randomOnCondition(input)
output[0] == output0
output[1] == output1
where:
input || output0 | output1
2 || 2 | 2
1 || 1 | _ //for somecase , can it skip assert?
}
好像没办法,我应该把案子一分为二
【问题讨论】:
-
您可以在
expect部分中使用常规代码作为断言。所以例如randomOnCondition(input)[0] == expected并将预期/输出部分更改为 int -
谢谢@OnnoRouast,你给了我第一个回复!我已经更新了这个问题。在这个问题上,我还需要检查第二个结果。仅断言第一个是不够的。有什么建议吗?
-
对于不需要验证的情况,例如将
null传递给输出1,然后只检查条件块if (output1) { x == y }中的条件。此外,您只需要一个|分隔符,而不是两个!您可以使用given:...then:块代替expect:,如果要在其中定义变量,请在given块中进行。 -
不要把简单的事情复杂化。拆分该方法,因为显然有两种不同的情况要测试:一种情况是检查两个值,另一种情况是选择性地只检查一个值。确保特征方法有很好的名称来解释它们的作用并对结果感到满意(如“可读代码”)。
-
+1 用于拆分测试。如果这是一个随机数据或顺序问题,那么你最好测试两个不同的东西并测试不同的属性。例如。即使不可预测,也可能该值必须在一个范围内,或者其他结果的数量必须是一个固定值等...