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.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.