使用文件作为输入的Camel Mock测试

时间:2016-01-27 08:50:20

标签: apache-camel

我想为Camel路线创建一个模拟测试,它使用文件作为输入:

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

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

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

我想必须有更好的方法,而不需要更改原始的Spring XML文件。有帮助吗? 谢谢

1 个答案:

答案 0 :(得分:3)

您可以在from语句中使用属性,然后替换测试中的属性,也可以使用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();
    }

}