295.4. 单元测试 Camel 路由


服务组件是一个 POJO,对于(非 OSGi)单元测试没有特殊要求。然而,有一些特定于 Camel SCR 的技术或只进行测试。

以下是一个单元测试示例,由 camel-archetype-scr 生成:

// This file was generated from org.apache.camel.archetypes/camel-archetype-scr/2.15-SNAPSHOT
package example;

import java.util.List;

import org.apache.camel.scr.internal.ScrHelper;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockComponent;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RouteDefinition;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class CamelScrExampleTest {

    Logger log = LoggerFactory.getLogger(getClass());

    @Rule
    public TestName testName = new TestName();

    CamelScrExample integration;
    ModelCamelContext context;

    @Before
    public void setUp() throws Exception {
        log.info("*******************************************************************");
        log.info("Test: " + testName.getMethodName());
        log.info("*******************************************************************");

        // Set property prefix for unit testing
        System.setProperty(CamelScrExample.PROPERTY_PREFIX, "unit");

        // Prepare the integration
        integration = new CamelScrExample();
        integration.prepare(null, ScrHelper.getScrProperties(integration.getClass().getName()));
        context = integration.getContext();

        // Disable JMX for test
        context.disableJMX();

        // Fake a component for test
        context.addComponent("amq", new MockComponent());
    }

    @After
    public void tearDown() throws Exception {
        integration.stop();
    }

    @Test
    public void testRoutes() throws Exception {
        // Adjust routes
        List<RouteDefinition> routes = context.getRouteDefinitions();

        routes.get(0).adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                // Replace "from" endpoint with direct:start
                replaceFromWith("direct:start");
                // Mock and skip result endpoint
                mockEndpoints("log:*");
            }
        });

        MockEndpoint resultEndpoint = context.getEndpoint("mock:log:foo", MockEndpoint.class);
        // resultEndpoint.expectedMessageCount(1); // If you want to just check the number of messages
        resultEndpoint.expectedBodiesReceived("hello"); // If you want to check the contents

        // Start the integration
        integration.run();

        // Send the test message
        context.createProducerTemplate().sendBody("direct:start", "hello");

        resultEndpoint.assertIsSatisfied();
    }
}
Copy to Clipboard Toggle word wrap

现在,让我们来看看值得关注的位。

使用属性前缀

        // Set property prefix for unit testing
        System.setProperty(CamelScrExample.PROPERTY_PREFIX, "unit");
Copy to Clipboard Toggle word wrap

这样,您可以通过使用 "unit." 前缀来覆盖配置的部分。例如,n. from 覆盖用于单元测试。

前缀可用于处理您的路由可能运行的运行时环境之间的区别。将未更改的捆绑包移至开发、测试和生产环境是一个典型的用例。

从注解中获取测试配置

        integration.prepare(null, ScrHelper.getScrProperties(integration.getClass().getName()));
Copy to Clipboard Toggle word wrap

在这里,我们在测试中配置服务组件,其属性与 OSGi 环境中使用的相同属性相同。

模拟组件用于测试

        // Fake a component for test
        context.addComponent("amq", new MockComponent());
Copy to Clipboard Toggle word wrap

测试中没有的组件可以像这样一样模拟,以允许路由启动。

调整测试的路由

        // Adjust routes
        List<RouteDefinition> routes = context.getRouteDefinitions();

        routes.get(0).adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                // Replace "from" endpoint with direct:start
                replaceFromWith("direct:start");
                // Mock and skip result endpoint
                mockEndpoints("log:*");
            }
        });
Copy to Clipboard Toggle word wrap

Camel 的 AdviceWith 功能允许修改路由进行测试。

启动路由

        // Start the integration
        integration.run();
Copy to Clipboard Toggle word wrap

在这里,我们启动 Service 组件及其路由。

发送测试消息

        // Send the test message
        context.createProducerTemplate().sendBody("direct:start", "hello");
Copy to Clipboard Toggle word wrap

在这里,我们向测试中的路由发送消息。

返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat