使用 Apache Camel 进行单元测试

Jig*_*aik 0 apache-camel spring-boot-test

我想在骆驼路线下面进行测试。我在网上找到的所有示例都有以文件开头的路由,在我的情况下,我有一个 spring bean 方法,它每隔几分钟就会被调用一次,最后消息被转换并移动到 jms 和审计目录。

我对这条路线的写测试知之甚少。我目前在我的测试用例中的所有内容是 Mockito.when(tradeService.searchTransaction()).thenReturn(dataWithSingleTransaction);

from("quartz2://tsTimer?cron=0/20+*+8-18+?+*+MON,TUE,WED,THU,FRI+*")
.bean(TradeService.class)
.marshal()
.jacksonxml(true)
.to("jms:queue:out-test")
.to("file:data/test/audit")
.end();
Run Code Online (Sandbox Code Playgroud)

the*_*NOD 5

使用 Apache Camel 和 Spring-Boot 进行测试非常简单。

只需执行以下操作(下面的示例是一个抽象示例,只是为了提示您如何操作):

编写测试类

使用 Spring-Boot Annotations 配置测试类。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@RunWith(SpringRunner.class)
public class MyRouteTest {
    @EndpointInject(uri = "{{sourceEndpoint}}")
    private ProducerTemplate sourceEndpoint;
    ....
    public void test() {
        // send your body to the endpoint. See other provided methods too.
        sourceEndpoint.sendBody([your input]);
    }
}
Run Code Online (Sandbox Code Playgroud)

src/test/application.properties: 配置你的 Camel-Endpoints 像源和目标:

sourceEndpoint=direct:myTestSource
Run Code Online (Sandbox Code Playgroud)

提示:

使用 spring-boot 时,最好不要直接在路由中硬连线您的 start-Endpoint,而是使用application.properties. 这样可以更轻松地模拟单元测试的端点,因为您可以更改direct-Component 而不更改源代码。

这意味着而不是: from("quartz2://tsTimer?cron=0/20+*+8-18+?+*+MON,TUE,WED,THU,FRI+*") 你应该写: from("{{sourceEndpoint}}")

sourceEndpoint在您的application.propertiessourceEndpoint=quartz2://tsTimer?cron=0/20+*+8-18+?+*+MON,TUE,WED,THU,FRI+*

这样你也可以在不同的情况下使用你的路线。

文档

可以在此处找到有关如何使用 spring-boot 进行测试的良好文档:https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

对于 Apache Camel:http : //camel.apache.org/testing.html