如何使用 Groovy Spock 合并两个测试用例,其中 void 类型的方法一次成功,一次抛出异常

问题描述 投票:0回答:1

我有以下2个相同方法的测试用例。

第一个调用没有结果的服务(因为服务方法是

void
)。

第二个调用相同的服务,但结果出现异常。

如何使用 @Unroll 和

where
部分将这两个测试用例合并为一个?

测试1:

def "test is valid by case - valid"() {
    given: "data to validate"
    Data data = Mock()
    
    when: "trying to check if valid"
    def result = validationService.isValidByCriteria(data)

    then: "no exception is thrown"
    noExceptionThrown()
    and: "validation is called without exception"
    1 * validationLogic.validate(data)
    and: "no exception therefore true returns"
    result
}

测试2:

def "test is valid by case - invalid"() {
    given: "data to validate"
    Data data = Mock()
    
    when: "trying to check if valid"
    def result = validationService.isValidByCriteria(data)

    then: "no exception is thrown"
    noExceptionThrown()
    and: "validation is called with exception"
    1 * validationLogic.validate(data) >> {throw new Exception()}
    and: "exception therefore false returns"
    !result
}
java validation filter groovy spock
1个回答
0
投票

我不确定您是否应该将这两个测试合并为一个测试,因为它们代表不同的功能行为。不过,我理解您减少重复代码的动机。

我猜你的情况大概是这样的:

class ValidationService {
  ValidationLogic validationLogic

  boolean isValidByCriteria(Data data) {
    try {
      validationLogic.validate(data)
    }
    catch (Exception e) {
      println "Validation error: $e.message"
      return false
    }
    return true
  }
}
class ValidationLogic {
  void validate(Data data) {
    if (data.name.contains('x'))
      throw new Exception('invalid data')
  }
}
class Data {
  String name
}

然后您的原始测试将按给定的方式运行。统一这两种方法的一种方法如下所示:

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

class ValidationServiceTest extends Specification {
  def validationLogic = Mock(ValidationLogic)
  def validationService = new ValidationService(validationLogic: validationLogic)

  @Unroll('#resultType result')
  def 'validation service returns normally'() {
    given: 'data to validate'
    Data data = Mock()

    when: 'trying to check if valid'
    def result = validationService.isValidByCriteria(data)

    then: 'no exception is thrown'
    noExceptionThrown()
    and: 'validation is called with exception'
    1 * validationLogic.validate(data) >> { if (!expectedResult) throw new Exception('oops') }
    and: 'exception therefore false returns'
    result == expectedResult

    where:
    resultType | expectedResult
    'valid'    | true
    'invalid'  | false
  }
}

在 IntelliJ IDEA 中,展开的功能表示如下:

Groovy Web Console 中尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.