简体   繁体   English

grails 单元测试中的存根方法

[英]Stub method in grails unit test

I have a unit test that does not seem to pass.我有一个似乎没有通过的单元测试。 :( :(

{
    given:
    Date currentDate = new Date()
    DateUtils.getCurrentDate() >> currentDate
    BigDecimal amount = 5
    long paymentMethodId = 4L
    Date fiveMinutesBeforeCurrentDate = new Date()

    use (TimeCategory) {
        fiveMinutesBeforeCurrentDate = currentDate-5.minutes
    }

    PaymentDetails details = Mock(PaymentDetails)
    PaymentDetails.findByIdAndAmountAndDateCreatedGreaterThanEquals(paymentMethodId, amount, fiveMinutesBeforeCurrentDate) >> details

    when:
    service.validatePaymentDetails(paymentMethodId, amount)

    then:
    thrown InvalidOperationException
}

The error always seems "No exception was thrown".错误总是看起来“没有抛出异常”。 The method validatePaymentDetails should throw an exception if the value of details is not null.如果details的值不是 null,则方法validatePaymentDetails应该抛出异常。

Thank you for your help!谢谢您的帮助!

Given a service like this:给定这样的服务:

class PaymentService {

    void validatePaymentDetails(long paymentMethodId, BigDecimal amount) {
        if(PaymentDetails.findByIdAndAmountAndDateCreatedGreaterThanEquals(paymentMethodId, amount, new Date()) != null) {
            throw new InvalidOperationException()
        }
    }
}

A unit test that would make sure that InvalidOperationException is thrown whenever PaymentDetails.findByIdAndAmountAndDateCreatedGreaterThanEquals returns something other than null could look like this:确保在PaymentDetails.findByIdAndAmountAndDateCreatedGreaterThanEquals返回null以外的其他内容时引发InvalidOperationException的单元测试可能如下所示:

import grails.testing.gorm.DataTest
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification

class PaymentServiceSpec extends Specification implements ServiceUnitTest<PaymentService>, DataTest{

    @Override
    Class[] getDomainClassesToMock() {
        [PaymentDetails]
    }

    void "test payment details validation"() {
        given:
        BigDecimal amount = 5
        long paymentMethodId = 4L

        GroovySpy(PaymentDetails, global: true)

        def details = new PaymentDetails()
        1 * PaymentDetails.findByIdAndAmountAndDateCreatedGreaterThanEquals(_, _, _) >> details

        when:
        service.validatePaymentDetails(paymentMethodId, amount)

        then:
        thrown InvalidOperationException
    }
}

I hope that helps.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM