Spock:如何忽略或跳过证明案件?

问题描述

使用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?
}

似乎没有解决办法,我应该将案件一分为二

解决方法

以下是我在上一条评论中解释的示例:

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