Camel ルートを開発したあと、想定通りに動作しているかを確認するためにテストを書きたいと思うことは多いはずです。
この記事では、**Apache Camel(XML DSL)**を前提に、JUnit 5 を使って Camel のルートをテストする方法を紹介します。
対象とするルート構成
以下のような簡単な Camel ルートを想定します:
-
direct:start
でメッセージを受け取る - Java の
Processor
を経由してメッセージ本文を変換 -
mock:result
に出力
1. ルート定義(camel-context.xml)
<routes xmlns="http://camel.apache.org/schema/spring">
<route id="sampleRoute">
<from uri="direct:start"/>
<to uri="bean:myProcessor"/>
<to uri="mock:result"/>
</route>
</routes>
2. Processor クラス
@Component("myProcessor")
public class MyProcessor implements Processor {
@Override
public void process(Exchange exchange) {
String body = exchange.getMessage().getBody(String.class);
exchange.getMessage().setBody(body.toUpperCase());
}
}
3. テストクラス(JUnit 5)
@CamelSpringBootTest
@SpringBootTest
@TestPropertySource("classpath:application-test.properties")
public class SampleRouteTest {
@Autowired
private ProducerTemplate producerTemplate;
@EndpointInject("mock:result")
private MockEndpoint mockResult;
@BeforeEach
void setup() {
mockResult.reset();
}
@Test
void testRouteProcessesMessage() throws Exception {
mockResult.expectedMessageCount(1);
mockResult.expectedBodiesReceived("HELLO");
producerTemplate.sendBody("direct:start", "hello");
mockResult.assertIsSatisfied();
String actual = mockResult.getExchanges().get(0).getMessage().getBody(String.class);
Assertions.assertEquals("HELLO", actual);
}
}
4. pom.xml に必要な依存関係
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-test-spring-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
解説ポイント
項目 | 内容 |
---|---|
@CamelSpringBootTest |
CamelContext を含めたテスト環境を起動 |
ProducerTemplate |
Camel ルートへメッセージ送信するためのAPI |
MockEndpoint |
受信メッセージの件数・内容を検証 |
getMessage() |
Camel 4 の標準的な API |
テストの流れまとめ
-
direct:start
に"hello"
を送信 -
myProcessor
で"HELLO"
に変換 -
mock:result
で受信し、内容が"HELLO"
であることを検証
まとめ
- Apache Camel(XML DSL)でも、
@CamelSpringBootTest
を使えば簡単にルートのテストが可能です。 -
mock:
エンドポイントを使えば、Camel のルートの挙動を柔軟にテストできます。 - テストごとに
mock.reset()
を入れておくと状態の影響を防げます。
mockの本番利用には注意!
なお、Camel の mock:
は 受信したメッセージ(Exchange)をメモリ上に保持し続けるため、
負荷テストや本番環境で使用するとヒープメモリを圧迫し、OOM(OutOfMemoryError)の原因になることがあります。
詳しくは以下の記事を参照してください: