@Test def "should return status aborted, if it was aborted"() { given: def orderA = createOrderModel() def orderB = createOrderModel() hitachiOrderService.process() >> [orderA, orderB] def stub = Stub(CronJobModel) { getRequestAbort() >> false >> true } when: def result = cronJob.perform(stub)
// check invocation: then: "first order was processed" 1 * updateOrderStatusStrategy.updateOrderStatus(orderA, "on verification") 1 * hitachiProcessDefinitionFactory.getFulfillmentProcess(_ as OrderModel) >> Stub(OrderProcessModel) 1 * businessProcessService.startProcess(_ as OrderProcessModel) and: "processing was aborted" result.status == CronJobStatus.ABORTED result.result == CronJobResult.SUCCESS }
You can simple check the different numbers of invocations:
1 2 3 4 5 6
1 * modelService.save(order) // exactly one call 0 * modelService.save(order) // zero calls (3..7) * modelService.save(order) // between three and seven calls (inclusive) (1.._) * modelService.save(order) // at least one call (_..3) * modelService.save(order) // at most three calls _ * modelService.save(order) // any number of calls, including zero
Call to any mock object
1 2
1 * modelService.save(order) // a call to 'modelService' 1 * _.save(order) // a call to any mock object
for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@Test def "test feature"() { given: def status = OrderStatus.IN_PROGRESS def order = Mock(OrderModel) when: nasaStatusStrategy.setStatus(status, order)
then: nasaAppointmentStrategy.hasAppointment() >> false and: // a call to 'modelService' 1 * modelService.save(order) // a call to any mock object 0 * _.setStatus(status) }
Call any method
The same way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 * modelService._(*_) // any method on modelService, with any argument list 1 * modelService._ // the same
1 * _._ // any method call on any mock object 1 * _ // the same
1 * modelService.save(order) // an argument that is equal to the object "order" 1 * modelService.save(!order) // an argument that is unequal to the object "order" 1 * modelService.save(_) // any single argument (including null) 1 * modelService.saveAll(*_) // any argument list (including the empty argument list) 1 * modelService.save(!null) // any non-null argument 1 * modelService.save(_ as OrderModel)// any non-null argument that is-a OrderModel 0 * modelService.save(_ as OrderModel)// don't allow save any orders order.setCode(endsWith("22")) // a String argument ending with "22"
then: 1 * netflixRatingValidator.validate(*_) // any method on customerFacade, with any argument list: 0 * customerFacade._(*_) and: thrown(ValidationException) } }
More options for stubbing
It works the same way:
1 2 3 4 5 6 7
modelService.clone(_ as OrderModel) >> Mock(OrderModel) // sequence: modelService.clone(_ as OrderModel) >>> [order1, order2, order3] // throw exception: modelService.save(order) >> { thrownew ModelSavingException("ups") } // return any non null value modelService.clone(_ as OrderModel) >> _