使用文件作为输入的骆驼模拟测试

Camel Mock test using file as input

我想为使用文件作为输入的 Camel 路由创建模拟测试:

<route id="myroute">
    <from uri="file:/var/file.log&amp;noop=true" />
     . . .
</route>

到目前为止,我已经能够在路由的开头包含一个 "direct:start" 元素,并手动将文件包含为 body::

 context.createProducerTemplate().sendBody("direct:start", "data1-data2-data3");

我想一定有更好的方法可以做到这一点,而无需更改原始 Spring XML 文件。有什么帮助吗? 谢谢

您可以在 from-statement 中使用 属性 然后在测试中替换 属性,或者您可以使用 camel-test 的编织支持来修改测试路线。

这是后者的一个例子:

import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;

public class FooTest extends CamelTestSupport {

    private static final String URI_START_ENDPOINT = "direct:teststart";
    private static final String MY_ROUTE_ID = "MY_ROUTE";
    private static final String URI_END = "mock:end";

    @EndpointInject(uri = URI_START_ENDPOINT)
    private Endpoint start;

    @EndpointInject(uri = URI_END)
    private MockEndpoint unmarhsalResult;

    @Override
    public boolean isUseAdviceWith() {
        return true;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        // return new MyRouteBuilder();
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("file:/var/file.log&noop=true").routeId(MY_ROUTE_ID)
                    .log("Content: ${body}");
            }
        };
    }

    @Override
    protected void doPostSetup() throws Exception {
        context.getRouteDefinition(MY_ROUTE_ID).adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                replaceFromWith(URI_START_ENDPOINT);
                weaveAddLast().to(URI_END);
            }
        });
        context.start();
    }

    @Test
    public void testUnmarshal() throws Exception {
        unmarhsalResult.expectedMessageCount(1);
        template.sendBody(URI_START_ENDPOINT, FileUtils.readFileToString(new File("src/test/resources/my_test_file.txt")));

        unmarhsalResult.assertIsSatisfied();
    }

}