RabbitListenerTestHarness在侦听器中注入实际对象

时间:2018-11-04 00:59:08

标签: java spring junit spring-amqp spring-rabbitmq

场景: Junit用于微服务,它在提取数据后侦听队列并发布到RabbitMQ中的交换。

问题:

  

RabbitListenerTestHarness正在为Rabbit创建模拟对象   仅侦听器类,正在为实例化实际对象   监听器自动装配组件

我找不到手动将模拟bean注入侦听器的方法。这会导致Junit在Junit执行期间将测试消息发布到微服务中配置的实际队列中。

解决方法::我可以使用Rabbit-test项目的唯一方法是配置测试交换以在Junit执行期间发布消息。

查询: 我想了解一下,是否有更好的方法为Rabbit Listener编写Junit。我也想了解是否有一种方法可以将模拟对象手动注入到Rabbit Listeners自动装配组件中。

示例代码段:

兔子监听器类

@RabbitListener(id = "id", bindings = @QueueBinding(value = @Queue(value = "sampleQueue", durable = "true", autoDelete = "false"),key = "sampleRoutingKey", exchange = @Exchange(value = "sampleExchange", durable = "true", ignoreDeclarationExceptions = "true", type = EXCHANGE_TYPE)))
public void getMessageFromQueue(@Payload EventModel event) throws ListenerExecutionFailedException, JAXBException {
    dataExporterService.exportDataAndPostToRabbit(event);
}

服务等级

@Autowired
DataExtractorRepository dataExtractorRepository;
@Autowired
DataPublihserRepository dataPublisherRepo;
public void exportDataAndPostToRabbit(EventModel event) throws JAXBException {
        dataPublisherRepo.sendMessageToExchange(dataExtractorRepository.extractOrderData(event), exchangeName, routingKeyValue);
}

DataPublihserRepository具有内部自动装配的RabbitTemplate。 DataExtractorRepository内部连接到DB以检索消息。

测试课程

@Autowired
private RabbitListenerTestHarness harness;

@Autowired
private RabbitTemplate rabbitTemplate;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DataExporterController = this.harness.getSpy("id");
}

@Test
public void shouldReceiveMessage() throws Exception {
LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
doAnswer(answer).when(DataExporterController).getMessageFromQueue(any(EventModel.class));
rabbitTemplate.convertAndSend("sampleExchange", "sampleRoutingKey", createMessage());
assertTrue(answer.getLatch().await(10, TimeUnit.SECONDS));
verify(DataExporterController, times(1)).getMessageFromQueue(any(OrderEventsModel.class));
verify(orderDataExporterController, times(1)).getMessageFromQueue(any(OrderEventsModel.class));
}

 private Message createMessage() {
        String inputObject = "{\"id\":12345}";
        MessageProperties props = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_JSON).build();
        return new Message(inputObject.getBytes(), props);
}

1 个答案:

答案 0 :(得分:1)

该工具旨在用作一种机制,以验证在集成测试中侦听器是否已接收到数据。要对监听器进行单元测试,请调用其onMessage方法。

例如,使用给定的Mockito

public class MyListener {

    @Autowired
    private SomeService service;

    @RabbitListener(id = "myListener", queues = "foo")
    public void listen(Foo foo) {
        this.service.process(foo);
    }

}

public interface SomeService {

    void process(Foo foo);

}

然后

@RunWith(SpringRunner.class)
public class So53136882ApplicationTests {

    @Autowired
    private RabbitListenerEndpointRegistry registry;

    @Autowired
    private SomeService service;

    @Test
    public void test() throws Exception {
        SimpleMessageListenerContainer container = (SimpleMessageListenerContainer) this.registry
                .getListenerContainer("myListener");
        ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener();
        Message message = MessageBuilder.withBody("{\"bar\":\"baz\"}".getBytes())
                .andProperties(MessagePropertiesBuilder.newInstance()
                        .setContentType("application/json")
                        .build())
                .build();
        listener.onMessage(message, mock(Channel.class));
        verify(this.service).process(new Foo("baz"));
    }

    @Configuration
    @EnableRabbit
    public static class config {

        @Bean
        public ConnectionFactory mockCf() {
            return mock(ConnectionFactory.class);
        }

        @Bean
        public MessageConverter converter() {
            return new Jackson2JsonMessageConverter();
        }

        @Bean
        public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
            SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
            factory.setConnectionFactory(mockCf());
            factory.setMessageConverter(converter());
            factory.setAutoStartup(false);
            return factory;
        }

        @Bean
        public MyListener myListener() {
            return new MyListener();
        }

        @Bean
        public SomeService service() {
            return mock(SomeService.class);
        }

    }

}

请注意,容器工厂不会启动侦听器容器。

对于测试发布,请注入由RabbitOperations实现的模拟RabbitTemplate

例如,给定

public class SomeServiceImpl implements SomeService {

    @Autowired
    private RabbitOperations rabbitOperations;

    @Override
    public void process(Foo foo) {
        this.rabbitOperations.convertAndSend(
                "someExchange", "someRoutingKey", new Foo(foo.getBar().toUpperCase()));
    }

}

@Bean
public SomeService service() {
    return new SomeServiceImpl();
}

@Bean
public RabbitOperations rabbitTemplate() {
    return mock(RabbitOperations.class);
}

然后

@Test
public void test() throws Exception {
    SimpleMessageListenerContainer container = (SimpleMessageListenerContainer) this.registry
            .getListenerContainer("myListener");
    ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener();
    Message message = MessageBuilder.withBody("{\"bar\":\"baz\"}".getBytes())
            .andProperties(MessagePropertiesBuilder.newInstance()
                    .setContentType("application/json")
                    .build())
            .build();
    listener.onMessage(message, mock(Channel.class));
    verify(this.rabbitTemplate).convertAndSend("someExchange", "someRoutingKey", new Foo("BAZ"));
}