按照这个问题,我正在尝试使用阻塞变量进行异步测试
Verify Spock mock with specified timeout
我只想知道已经调用了end方法。我尝试复制接受的答案,但从未设置阻塞变量。
阻塞变量只是超时。
所以我有
@TestConfiguration
static class ITRouterConfiguration {
private DetachedMockFactory factory = new DetachedMockFactory()
@Bean
IVoucherService voucherService() {
return factory.Mock(IVoucherService)
}
}
@Autowired
private IVoucherService voucherService
def 'Should create a voucher'() {
MockQueue mockQueue = mockDestinationManager.createQueue("SERVICE_REQUEST")
Assert.assertNotNull(jmsTemplate);
Assert.assertNotNull(mockDestinationManager);
given:
def result = new BlockingVariable<Boolean>(0.2) // 200ms
voucherService.createVoucher() >> {
result.set(true)
}
when: 'a message is sent'
jmsTemplate.send(mockQueue, new MessageCreator() {
@Override
Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage(BODY)
message.setStringProperty(ACTION_TYPE, CREATE)
return message
}
})
//sleep(2000)
then: 'check create voucher was called once'
result.get()
}
BlockingVariable.get() timed out after 10.00 seconds
at spock.util.concurrent.BlockingVariable.get(BlockingVariable.java:113)
at uk.co.cpp.servicerequestrouter.CreateVoucherSpec.Should create a voucher(CreateVoucherSpec.groovy:81)
如果我保持睡眠状态并简单断言
1 * voucherService.createVoucher(_)
可以,但是我不想。
答案 0 :(得分:1)
您可以使用CountDownLatch。
given:
def latch = new CountDownLatch(1)
when: 'a message is sent'
jmsTemplate.send(mockQueue, new MessageCreator() {
@Override
Message createMessage(Session session) throws JMSException {
TextMessage message = session.createTextMessage(BODY)
message.setStringProperty(ACTION_TYPE, CREATE)
return message
}
})
latch.await(10, TimeUnit.SECONDS) // must be in when-block, use timeout variant
then: 'check create voucher was called once'
1 * voucherService.createVoucher(_) >> {
latch.countDown()
}