使用MockEndpoint测试Camel路由

时间:2011-12-19 02:56:55

标签: guice apache-camel

为什么这个测试失败了" java.lang.AssertionError:mock:// destino收到的消息计数。预期:< 12>但是:< 0>" ?我只是想测试Camel是否可以真正重新排序消息。

进口:

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.CamelContext;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.guice.CamelModuleWithRouteTypes;
import org.jukito.JukitoModule;
import org.jukito.JukitoRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.google.inject.Inject;

测试:

@RunWith(JukitoRunner.class) public class ResequenceTest {

    @Inject protected CamelContext context;
    @Produce protected ProducerTemplate template;

    public static class Module extends JukitoModule {
        @SuppressWarnings("unchecked") protected void configureTest() {
            install(new CamelModuleWithRouteTypes(OrderingTestRouteBuilder.class));
        }
    }

    @Test public void testDozenMsgsOrderByIntegerBody() throws Exception {
        // fail();
            Integer[] input = new Integer[] {12, 11, 10, 9, 8, 7, 6, 5, 1, 2, 3, 4};
            List<Integer> expectedOutput = new ArrayList<Integer>();
        for (int i=1; i<=12; i++) {expectedOutput.add(i);};
        for (Integer i : input) {template.sendBody("mock:receptor", i);};
        MockEndpoint resultEndpoint = context.getEndpoint("mock:destino", MockEndpoint.class);
        resultEndpoint.expectedBodiesReceived(expectedOutput);
        resultEndpoint.assertIsSatisfied();
    }

}

路线:

class OrderingTestRouteBuilder extends RouteBuilder {
        @Override public void configure() throws Exception {
        from("direct:start")
            .to("mock:receptor")
            .resequence(body(Integer.class))
            .to("mock:destino");
    }
}

谢谢, 鲁道夫

2 个答案:

答案 0 :(得分:5)

您应该在将消息发送到Camel之前设置模拟 之前的期望值。步骤是

  1. 设定对模拟的期望
  2. 发送消息
  3. 断言

答案 1 :(得分:1)

现在正在过去。我把测试改为:

@Test public void testDozenMsgsOrderByIntegerBody() throws Exception {
    // fail();
    List<Integer> input = Arrays.asList(new Integer[] {12, 11, 10, 9, 8, 7, 6, 5, 1, 2, 3, 4});
    List<Integer> expectedOutput = new ArrayList<Integer>();
    for (int i=1; i<=12; i++) {expectedOutput.add(i);};
    MockEndpoint resultEndpoint = context.getEndpoint("mock:result", MockEndpoint.class);
    resultEndpoint.expectedBodiesReceived(expectedOutput);
    for (Integer i : input) {template.sendBody("direct:start", i);};
    resultEndpoint.assertIsSatisfied();
}

和路线:

class OrderingTestRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
    from("direct:start")
       .resequence(body(Integer.class))
       .to("mock:result");
    }
}