Camel测试模板使用与我发送的交换不同的交换

时间:2015-11-24 18:24:59

标签: java apache-camel

我有以下测试:

public class MyTest extends CamelSpringTestSupport {

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext(new String[] {
                "classpath:my-config.xml",
                });
    }

    @Test
    public void testSomething() throws Exception {

        Exchange exchange = new DefaultExchange(context);
        exchange.getIn().setHeader("myId", "1234");
        MessageContentsList parameters = new MessageContentsList();
        parameters.add(0, "");
        parameters.add(1, "1234");
        exchange.getIn().setBody(parameters);

        System.out.println("exchange before = " + System.identityHashCode(exchange)); //1657040467

        template.send("direct:myRoute", exchange);

        Object object = exchange.getOut().getBody();

        System.out.println("result = " + object); //null
        System.out.println("exchange after = " + System.identityHashCode(exchange)); //1657040467

        assertFalse(exchange.isFailed());
    }
}

这是路线内的最后一步"直接:myRoute":

public void doSomething(Exchange exchange)
{
    System.out.println("exchange within = " + System.identityHashCode(exchange)); //1649140180

    exchange.getOut().setBody(1);
}

我的路由由RouteBuilder类定义,我按

加载它们
<camelContext id="mainContext" xmlns="http://camel.apache.org/schema/spring">

    <packageScan>
        <package>com.my.route</package>
    </packageScan>

</camelContext>

并且还通过代码动态生成:

((CamelContext) applicationContext.getBean("mainContext")).addRoutes(routeBuilder);

正如您所看到的,当我从测试中调用路由时,我无法检索路由的输出,因为在测试中由于某种原因它是一个不同的交换对象(但是,原始的交换头和属性以某种方式被复制到路线内的交换)。 当我通过XML定义路由时,不会发生此问题。

为什么这样,当我从测试中调用它时,如何检索路由的结果?

1 个答案:

答案 0 :(得分:2)

我不是百分百肯定,但我认为你不能这样写。

template.send("direct:myRoute", exchange);
Object object = exchange.getOut().getBody();

理想情况应该是:

    Exchange out=null;
    out=template.requestBody("direct:myRoute", exchange);
    String body=out.getOut().getBody();

为此,您需要将交换模式设置为InOut。 有关模板的更多信息: https://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/ProducerTemplate.html