在单元测试 class 中从 mockEndPoint 获取 Camel 路由未按预期运行的 getExchange

getExchange from mockEndPoint in a unit-test class for Camel Route Not Behaving As Expected

我想在 Camel Route 的单元测试 class 中从 mockEndPoint 获取 getExchange,但它不起作用。

这是我的单元测试 class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:camel-unit-test.xml")
public class ImportDatabaseRouteTest extends CamelTestSupport {
    @Value("${sql.importDatabase}")
    String oldEndPoint;

    @Autowired
    private ImportDatabaseRoute importDatabaseRoute;

    @Autowired
    private DriverManagerDataSource dataSource;

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

    @Before
    public void mockEndpoints() throws Exception {
        AdviceWithRouteBuilder adviceTest = new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint(oldEndPoint)
                        .skipSendToOriginalEndpoint()
                        .to("mock:catchCSVList");
            }
        };
        context.getRouteDefinitions().get(0).adviceWith(context, adviceTest);
    }

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

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        //use jndi.bind to bind your beans
        jndi.bind("dataSource", dataSource);
        return jndi;
    }
    @Test
    public void testTheImportRoute() throws Exception {
        MockEndpoint mockEndPointTest = getMockEndpoint("mock:catchCSVList");
        context.start();
        List<List<String>> test = (List<List<String>>) mockEndPointTest.getExchanges().get(0).getIn().getBody();
        assertEquals("4227",test.get(1).get(0));
        assertEquals("370",test.get(1).get(1));
        assertEquals("",test.get(1).get(2));
        mockEndPointTest.expectedMessageCount(1);
        mockEndPointTest.assertIsSatisfied();
        context.stop();
    }

}

结果如下: java.lang.ArrayIndexOutOfBoundsException: 0

at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:387)

请帮我解决一下。非常感谢。

您必须在获得交换之前声明模拟。因为这些交换是到达模拟的 实际 交换。所以它的期望必须首先得到满足,即 1 条消息应该到达。如果那是成功的,那么你可以通过索引 0 进行交换,并且你不会得到 IndexOutOfBoundsException

    MockEndpoint mockEndPointTest = getMockEndpoint("mock:catchCSVList");
    context.start();

    // set expectations on mock here
    mockEndPointTest.expectedMessageCount(1);
    mockEndPointTest.assertIsSatisfied();

    // okay now we can get the exchange's from the mock
    List<List<String>> test = (List<List<String>>) mockEndPointTest.getExchanges().get(0).getIn().getBody();
    assertEquals("4227",test.get(1).get(0));
    assertEquals("370",test.get(1).get(1));
    assertEquals("",test.get(1).get(2));

    context.stop();