【问题标题】:Spock: how to ignore or skip certian case?Spock:如何忽略或跳过某些情况?
【发布时间】: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 用于拆分测试。如果这是一个随机数据或顺序问题,那么你最好测试两个不同的东西并测试不同的属性。例如。即使不可预测,也可能该值必须在一个范围内,或者其他结果的数量必须是一个固定值等...

标签: java groovy spock


【解决方案1】:

这是我在之前评论中解释的示例:

package de.scrum_master.stackoverflow.q63355662

import spock.lang.Specification
import spock.lang.Unroll

class SeparateCasesTest extends Specification {
  int[] randomOnCondition(int input) {
    def output = input % 2 ? Random.newInstance().nextInt() : input
    [input, output]
  }

  @Unroll
  def "predictable output for input #input"() {
    expect:
    randomOnCondition(input) == output

    where:
    input || output
    2     || [2, 2]
    4     || [4, 4]
    6     || [6, 6]
  }

  @Unroll
  def "partly unpredictable output for input #input"() {
    expect:
    randomOnCondition(input)[0] == firstOutputElement

    where:
    input || firstOutputElement
    1     || 1
    3     || 3
    5     || 5
  }
}

更新:与您的问题有些无关,但如果输出确实包含输入值,则可以简化您的测试:

  @Unroll
  def "predictable output for input #input"() {
    expect:
    randomOnCondition(input) == [input, input]

    where:
    input << [2, 4, 6]
  }

  @Unroll
  def "partly unpredictable output for input #input"() {
    expect:
    randomOnCondition(input)[0] == input

    where:
    input << [1, 3, 5]
  }

【讨论】:

  • 在 SO 上感谢人们的常用方法是通过单击旁边的灰色复选标记来接受答案,从而关闭问题。因此,如果您认为我的回答是正确的,请这样做。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多