Camel Mock test using file as input

柔情痞子 提交于 2020-01-03 03:33:06

问题


I want to create a Mock Test for a Camel route which uses as input a file:

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

So far I have been able to include a "direct:start" element at the beginning of the route and include manually the file as body::

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

I guess there must be a better way for doing it, without changing the original Spring XML file. Any help ? Thanks


回答1:


You can either use a property in your from-statement and then replace the property in the test, or you can use camel-test's weaving support to modify the route for test.

Here's an example of the latter:

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();
    }

}


来源:https://stackoverflow.com/questions/35032612/camel-mock-test-using-file-as-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!