groovy 异步测试是否已调用远程方法

62o28rlo  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(230)

我尝试在异步测试中使用阻塞变量,下面的问题
Verify Spock mock with specified timeout
我只想知道一个结束方法已经被调用了。我试着复制接受的答案,但是阻塞变量从未被设置。
阻塞变量只是超时。
所以我有

@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)

如果我离开睡眠和简单的Assert
这很有效,但我不想

rjzwgtxy

rjzwgtxy1#

您可以使用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()
    }
jogvjijk

jogvjijk2#

目前我也遇到了这个问题,这是因为voucherService不是一个模拟对象,所以存根不会工作,你应该用@SpringSpy来注解它

相关问题