Apache Camel - 创建模拟端点以侦听从处理器内发送的消息

时间:2018-03-14 09:14:45

标签: apache-camel

我的路线如下:

                from(fromEndpoint).routeId("ticketRoute")
                .log("Received Tickets  : ${body}")
                .doTry()
                .process(exchange -> {
                    List<TradeTicketDto> ticketDtos = (List<TradeTicketDto>) exchange.getIn().getBody();
                    ticketDtos.stream()
                            .forEach(t -> solaceMessagePublisher.sendAsText("BOOKINGSERVICE.TICKET.UPDATED", t));
                    ticketToTradeConverter.convert(ticketDtos)
                            .forEach(t -> solaceMessagePublisher.sendAsText("BOOKINGSERVICE.TRADE.UPDATED", t));
                }).doCatch(java.lang.RuntimeException.class)
                .log(exceptionMessage().toString() + " --> ${body}");

solaceMessagePublisher是应用程序中的一个实用程序类,它对传递的对象(第二个参数)执行一些操作,最后将其转换为json字符串并发送到jms主题(第一个参数)。

SolaceMessagePublisher.java

public void sendAsText(final String destinationKey, Object payload) {
        LOGGER.debug("Sending object as text to %s",destinationKey);
        String destinationValue = null;
        if (StringUtils.isNotEmpty(destinationKey)) {
            destinationValue = properties.getProperty(destinationKey);
        }
        LOGGER.debug("Identified Destination Value  = %s from key %s", destinationValue,destinationKey);
        if (StringUtils.isEmpty(destinationValue)) {
            throw new BaseServiceException("Invalid destination for message");
        }

        sendAsTextToDestination(destinationValue, payload);
    }

    public void sendAsTextToDestination(final String destinationValue, Object payload) {
        if (payload == null) {
            LOGGER.debug(" %s %s",EMPTY_PAYLOAD_ERROR_MESSAGE, destinationValue);
            return;
        }

        final String message = messageCreator.createMessageEnvelopAsJSON(payload, ContextProvider.getUserInContext());

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Created message = " + message);
        }
        jmsTemplate.send(destinationValue, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                LOGGER.debug("Creating JMS Text Message");
                return session.createTextMessage(message);
            }
        });
    }

我在创建模拟端点以侦听发送到此主题的消息时遇到问题。问题是如何收听发送到骆驼上下文之外的主题的消息?

我使用mock尝试了我的测试:jms:endpoint。它不起作用。

我的测试如下

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SiteMain.class })
public class TicketRouteCamelTest extends CamelSpringTestSupport{

    @Autowired
    protected BaseMessageEnvelopCreator messageCreator;

    private static final String MOCK_TICKET_UPDATED_QUEUE = "direct:mockTicketUpdated";

    @Before
    public void configureMockEndpoints() throws Exception {

        //mock input
        final AdviceWithRouteBuilder mockRouteAdvice = new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                replaceFromWith(MOCK_TICKET_UPDATED_QUEUE);
            }
        };

        context().getRouteDefinition("ticketRoute").adviceWith(context(), mockRouteAdvice);
    }

    @Test
    public void testTicketRouteWithListOfTickets() throws Exception {
        //create test data
        TradeTicketDto tradeTicketDto = TradeTestDataHelper.getTradeTicketDto();

        //create an exchange and set its body with test data
        List<TradeTicketDto> list = new ArrayList<>();
        list.add(tradeTicketDto);
        list.add(tradeTicketDto);
        Exchange requestExchange = ExchangeBuilder.anExchange(context()).build();
        requestExchange.getIn().setBody(list);

        //create assert on the mock endpoints
        MockEndpoint mockTicketUpdatedEndpoint = getMockEndpoint("mock:DEV/bookingservice/ticket/updated");
        mockTicketUpdatedEndpoint.expectedBodiesReceived(
                messageCreator.createMessageEnvelopAsJSON(list.get(0), ContextProvider.getUserInContext()),
                messageCreator.createMessageEnvelopAsJSON(list.get(1), ContextProvider.getUserInContext()) );

        MockEndpoint mockTradeUpdatedEndpoint = getMockEndpoint("mock:DEV/bookingservice/trade/updated");
        mockTradeUpdatedEndpoint.expectedBodiesReceived(
                messageCreator.createMessageEnvelopAsJSON(list.get(0).getTicketInstruments().get(0), ContextProvider.getUserInContext()),
                messageCreator.createMessageEnvelopAsJSON(list.get(0).getTicketInstruments().get(1), ContextProvider.getUserInContext()),
                messageCreator.createMessageEnvelopAsJSON(list.get(1).getTicketInstruments().get(0), ContextProvider.getUserInContext()),
                messageCreator.createMessageEnvelopAsJSON(list.get(1).getTicketInstruments().get(1), ContextProvider.getUserInContext()));

        //send test exchange to request mock endpoint
        template.send(MOCK_TICKET_UPDATED_QUEUE, requestExchange);

        //test the asserts
        assertMockEndpointsSatisfied();
    }
}

在运行测试中,在mockendpont上收到的实际物体是0

1 个答案:

答案 0 :(得分:0)

Mock不是消费者/生产者交换数据的队列。它是一个用于测试目的的接收器,您可以在模拟上设置期望。

如果您想通过某种其他方式模拟JMS,请查看存根组件:http://camel.apache.org/stub

它还列在测试文档的底部:http://camel.apache.org/testing