【问题标题】:Spock unit test that a validation throws an exceptionSpock 单元测试验证抛出异常
【发布时间】:2014-06-24 11:32:17
【问题描述】:

我是 Spock 的新手,我想对这个类进行单元测试。在类中有一个验证产品的方法。要通过验证,产品必须具有 fullPrice 并且必须包含所有其他价格,否则应抛出异常。

class PriceValidator {
    private final Logger logger = Logger.getLogger(MyService.class)

    void validate (Product product) throws SubsystemException {

        if (!product.fullPrice || !product.fullPrice.priceInclVAT || !product.fullPrice.priceExclVAT || !product.fullPrice.vat) {
            String message = "No price found!"
            logger.error(message)
            throw new SubsystemException(
                    Subsystem.MySystem,
                    FailureCause.NO_PRICE_FOUND,
                    message
            )
        }
    }
}

我已经尝试以多种方式对此进行测试,但没有任何运气。我猜我需要模拟,但这对我来说也是新的。这是我尝试过的一个测试示例,导致“测试框架意外退出”(并且所有价格都是字符串):

class PriceValidatorTest extends Specification {

    @Unroll
    def "No price should throw an exception"() {
        given:
        PriceValidator priceValidator = new PriceValidator()
        Product product = Mock()

        when:
        product.fullPrice != null
        product.fullPrice.priceInclVAT = "100"
        product.fullPrice.priceExclVAT = "70"
        product.fullPrice.vat = null
        priceValidator.validate(product)

        then:
        thrown(SubsystemException)
    }
}

有人对如何测试 PriceValidator 有建议吗?

【问题讨论】:

  • 如果您觉得我的回答有用,请接受并点赞。

标签: validation unit-testing groovy intellij-idea spock


【解决方案1】:

您需要测试几个案例,其中之一是:

def "No price should throw an exception"() {
    given:
    PriceValidator priceValidator = new PriceValidator()
    Product product = Mock() {
        getFullPrice() >> null
    }

    when:
    priceValidator.validate(product)

    then:
    thrown(SubsystemException)
}

您需要模拟 Product 类的行为(>> rightShift 运算符的行)。不,它似乎已准备好进行测试。其他情况,当价格被填充时,应以单独的方法进行测试。还有其他问题吗?

【讨论】:

  • 谢谢。问题仍然存在,但我现在看到模拟有问题,说“无法将'对象'分配给'产品'。知道这里有什么问题吗?
  • 好的,然后试试Mock(Product)
  • 然后呢?进展如何?
  • 很抱歉回复太晚了。当我添加问题时,我是 Spock 的新手并且嘲笑。后来我意识到我什至不需要模拟。所以在“给定”下,我只是简单地创建了产品。产品 product = new Product(fullPrice: new Price(priceInclVAT: 100, priceExclVAT: 70, vat: null))
  • 请记住始终完成在 StackOverflow 上提问的过程(通过接受或投票)。有些人确实会奉献自己的时间来帮助您或任何其他人。
猜你喜欢
  • 2014-05-10
  • 2013-01-21
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
相关资源
最近更新 更多