如果查询结果,我的服务将抛出InvalidOperationException
PaymentDetails.findByIdAndAmountDateCreatedGreaterThanEquals
不为空
该功能旨在检查最近5分钟是否有重复的详细信息。
我正在尝试为此创建一个单元测试,但该函数始终返回NULL
given:
DateUtils.getCurrentDate() >> new Date()
Date currentDate = new Date()
Date twoMinutesBeforeCurrentDate = new Date()
use (TimeCategory) {
twoMinutesBeforeCurrentDate = currentDate - 2.minutes
}
long methodId = 3L
BigDecimal amount = new BigDecimal("5")
PaymentDetails details = new PaymentDetails(amount: amount, id:methodId).save(flush: true)
details.dateCreated = twoMinutesBeforeCurrentDate
details.save(flush: true)
when:
service.validateTransactionDetails(methodId, amount)
then:
InvalidOperationException exception = thrown()
ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION == exception.apiError
这是我的服务方法:
Date currentDate = DateUtils.getCurrentDate()
Date fiveMinutesBeforeCurrentDate = null
use (TimeCategory) {
fiveMinutesBeforeCurrentDate = currentDate-5.minutes
}
PaymentDetails details = PaymentDetails.findByIdAndAmountDateCreatedGreaterThanEquals(methodId, amount, fiveMinutesBeforeCurrentDate)
if (details) {
throw new InvalidOperationException(ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION)
}
先感谢您!这是我第一次从Grails调试某些东西,对此我感到很困难。请保持温柔。大声笑。
最佳答案
问题在于new PaymentDetails(amount: amount, id:methodId)
并不是真正有效,因为id
默认情况下不包含在mass属性绑定(bind)中,因此PaymentDetails
实例不具有您认为的id
(可以根据需要在调试器中检查对象来进行验证) 。更好的主意是让id
方法为实体分配一个save
,然后稍后检索该值以启动查询。这有效:
import grails.testing.gorm.DataTest
import grails.testing.services.ServiceUnitTest
import groovy.time.TimeCategory
import spock.lang.Specification
class PaymentServiceSpec extends Specification implements ServiceUnitTest<PaymentService>, DataTest{
@Override
Class[] getDomainClassesToMock() {
[PaymentDetails]
}
void "test payment details validation"() {
given:
Date currentDate = new Date()
GroovySpy(DateUtils, global: true)
1 * DateUtils.getCurrentDate() >> currentDate
Date twoMinutesBeforeCurrentDate
use (TimeCategory) {
twoMinutesBeforeCurrentDate = currentDate - 2.minutes
}
BigDecimal amount = new BigDecimal("5")
PaymentDetails details = new PaymentDetails(amount: amount).save(flush: true)
when:
service.validateTransactionDetails(details.id, amount)
then:
InvalidOperationException exception = thrown()
ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION == exception.apiError
}
}
希望对您有所帮助。