我测试正确吗?

时间:2013-10-21 09:14:44

标签: java unit-testing apache-camel

我有一个与Camel集成的spring应用,我想为它编写测试。这是我的应用程序:

驼-config.xml中

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <routeBuilder ref="converter" />
</camelContext>

<bean id="converter" class="Converter"/>

要测试的课程:

@Component
public class Converter extends SpringRouteBuilder {

@Override
public void configure() throws Exception {

    final XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
    xmlJsonFormat.setTypeHints(String.valueOf("YES"));

    from("ftp://Mike@localhost?" +
            "noop=true&binary=true&consumer.delay=5s&include=.*xml")
            .idempotentConsumer(header("CamelFileName"), FileIdempotentRepository.fileIdempotentRepository(new File("data", "repo.dat")))
            .marshal(xmlJsonFormat).to("file://data").process(
            new Processor() {
                //System.out.println();
            }
        });
   }
}

这是我的测试课:

public class RouteTest extends CamelTestSupport {

@Override
protected CamelContext createCamelContext() throws Exception {
    CamelContext context = super.createCamelContext();       
    context.addComponent("ftp", context.getComponent("seda"));
    return context;
}

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {                
            from("ftp://Mike@localhost").to("mock:quote");
        }
    };
}

@Test
public void testSameMessageArrived() throws Exception {
    MockEndpoint quote = getMockEndpoint("mock:quote");
    FileReader fl = new FileReader("D:\\test\\asdasd.txt");
    quote.expectedBodiesReceived(fl);
    template.sendBody("ftp://Mike@localhost", fl);
    quote.assertIsSatisfied();
}
}

此测试通过,但我不确定这是测试此特定程序的正确方法 如果我做得对,请你告诉我,还是我应该以其他方式进行测试?

1 个答案:

答案 0 :(得分:1)

更好的方法是不重写路线。请改用您的实际路线。

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new Converter();
}

然后使用camel-mock,这样可以拦截现有端点,如下所示:

context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
    @Override
    public void configure() throws Exception {
        // mock all endpoints
        mockEndpoints();
    }
});

getMockEndpoint("mock:direct:start").expectedBodiesReceived("Hello World");

或使用模式:

context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
    @Override
    public void configure() throws Exception {
        // mock only log endpoints
        mockEndpoints("log*");
    }
});

// now we can refer to log:foo as a mock and set our expectations
getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World");

如果您想了解有关Camel测试的更多信息,我认真建议您阅读“Camel in Action”一书。

编辑:以下是Claus Ibsen对类似问题的回复(stack)。

您可以使用专用或嵌入式FTP服务器进行集成测试,也可以使用模拟进行单元测试,具体取决于您要测试的内容。你也可以做到这两点。