在Camel中测试我的对象的正确方法

时间:2013-04-04 00:06:00

标签: java junit apache-camel

我正在尝试为Camel路线设置测试。我的测试路由读取二进制文件并将其发送到翻译器bean,返回POJO。现在,我想在POJO上做一些断言,以确保与已知值匹配的值。我认为标准的东西。在我看过的例子中,正文似乎总是一个字符串或原始类型,并且可以对它进行简单的断言。但是,就我而言,它是一个对象,所以我想以某种方式获取对象。

这是我到目前为止所尝试的内容:

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("file:///path/to/dir/of/test/file/?noop=true")
            .bean(TranslatorBean.class)
            .to("mock:test").end();
        }
    };
}

@Test
public void testReadMessage() throws Exception {

    MockEndpoint endpoint = getMockEndpoint("mock:test");

    endpoint.whenAnyExchangeReceived(new Processor() {      
        @Override
        public void process(Exchange exchange) throws Exception {           
            Object body = exchange.getIn().getBody();

            assertIsInstanceOf(MyPOJO.class, body);

            MyPOJO message = (MyPOJO) body;

            assertEquals("Some Field", someValue, message.getSomeField());

            // etc., etc.

        }           
    });


    //If I don't put some sleep here it ends before anything happens
    Thread.sleep(2000);

}

当我运行它时,它似乎正确运行,但当我单步执行时,我可以看到断言失败。出于某种原因,这不会被报道。

然后我尝试在路由中内联我的处理器:

public void configure() throws Exception {
    .from("file:///path/to/dir/of/test/file/?noop=true")
    .bean(TranslatorBean.class)
    .process(new Processor() {
        //same code as before
     });
}

这种作品,但有一个很大的问题。任何失败的断言仍然不会被JUnit报告。相反,它们被Camel捕获,并报告为CamelExecutionException,绝对没有关于原因的信息。只有通过单步执行调试器才能确定哪个断言失败。另外,这样我的整个测试都在configure方法中,而不是在自己的测试方法中。我必须在睡眠中加入一个空的测试才能让它运行。显然这很糟糕,但我确定这里做的正确的事情是什么。它看起来像处理器可能不是正确的路线,但我没有看到正确的方法。非常感谢任何指导。

2 个答案:

答案 0 :(得分:4)

如果您正在寻找一种方法来检索对象本身并对其执行断言,那么您需要以下内容:

Product resultProduct = resultEndpoint.getExchanges().get(0).getIn().getBody(Product.class);
assertEquals(expectedEANCode, resultProduct.getEANCode());

其中resultEndPoint是模拟端点。

答案 1 :(得分:1)

我建议从Apache Camel文档开始阅读。在用户指南中:http://camel.apache.org/user-guide.html有一个指向测试的链接:http://camel.apache.org/testing.html,其中包含大量信息。此外,既然你也使用了模拟端点:http://camel.apache.org/mock

例如,您拥有的模拟代码可以作为

完成
MockEndpoint endpoint = getMockEndpoint("mock:test");
mock.allMessages().body().isInstanceOf(MyPojo.class)

虽然人们经常在模拟端点等上使用所考虑的方法 例如,如果您期望2条消息,并且它们的正文按顺序排列为:

MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World", "Bye World");

但请查看模拟和测试文档以了解更多信息。

如果您有一本Camel in Action书的副本,那么请阅读第6章,其中包括使用Camel进行测试。