DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • Tooling Guide for Getting Started With Apache Camel in 2021
  • Building an Image Classification Pipeline With Apache Camel and Deep Java Library (DJL)
  • Effective Engineering Feedback: Software Testing

Trending

  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • You Learned AI. So Why Are You Still Not Getting Hired?
  • Context Is the New Schema
  • AWS Kiro: The Agentic IDE That Makes Specs the Unit of Work
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing With Apache Camel

Unit Testing With Apache Camel

Learn how to write unit test cases for Camel routes while taking advantage of its Java library and camel-test module to test your routes and integrations.

By 
Jitendra Bafna user avatar
Jitendra Bafna
·
Jan. 01, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
76.8K Views

Join the DZone community and get the full member experience.

Join For Free

1.0 Overview

Apache Camel provides a powerful Java library for testing your routes, and the camel-test module has been introduced to test your Enterprise Integration Patterns.

The camel-test JAR uses JUnit. There is an alternative camel-testng JAR (from Camel 2.8) using the TestNG test framework.

You will see various use cases for testing your Camel routes.

2.0 Use Case 1

2.1 Developing Routes to Move Files From One Folder to Another

Here, you can see that route is moving a file from one directory to another directory.

package com.learncamel.file;

import org.apache.camel.builder.RouteBuilder;

public class CopyFilesRoute extends RouteBuilder {

    public void configure() throws Exception{
        from("file:data/input?noop=true")
                .to("file:data/output");

    }

}

2.2 Writing a Test Case for the Route

The first thing you need to do is add a camel-test dependency in your POM.xml file or install the camel-test module. 

In the below example, the CopyFileRouteTest class will extend CamelTestSupport and override the createRouteBuilder method. This method will write the route CopyFilesRoute, defined above.

package com.learncamel.file;

import java.io.File;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class CopyFileRouteTest extends CamelTestSupport {

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new CopyFilesRoute();
    }

    @Test
    public void checkFileExistsInOutputDirectory() throws InterruptedException
    {
        Thread.sleep(5000);

        File file = new File("data/output");
        assertTrue(file.isDirectory());
        assertEquals(2,file.listFiles().length);

    }
}

The above code defines the method checkFileExistsInOutputDirectory(), the test cases which will check if the output directory exists and the number of files moved to output directory is 2.

3.0 Use Case 2

3.1 Developing a Simple Direct Route

Here, we will develop a simple route with a direct component.The direct: component provides direct, synchronous invocation of any consumers when a producer sends a message exchange.  

package com.learncamel.direct;

import org.apache.camel.builder.RouteBuilder;

public class SampleDirectRoute extends RouteBuilder{
    public void configure() throws Exception
    {
        from("direct:sampleInput")
                .log("Received Message is ${body} and Headers are ${headers}")
                .to("file:sampleOutput?fileName=output.txt");
    }
}

3.2 Writing Test Case for Route

You will see below test case will check if the file is the directory and it will verify the filename. 

package com.learncamel.direct;

import org.apache.camel.Exchange;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import java.io.File;

public class SampleDirectRouteTest extends CamelTestSupport {
    @Override
    public RouteBuilder createRouteBuilder() throws Exception
    {
        return new SampleDirectRoute();
    }

    @Test
    public void SampleTestRoute() throws InterruptedException{

        template.sendBody("direct:sampleInput","Hello");
        Thread.sleep(5000);

        File file=new File("sampleOutput");
        assertTrue(file.isDirectory());

        Exchange exchange = consumer.receive("file:sampleOutput");

        System.out.println("Received body is :" + exchange.getIn().getBody());
        System.out.println("File Name is :" + exchange.getIn().getHeader("CamelFileName"));
        assertEquals("output.txt", exchange.getIn().getHeader("CamelFileName"));
    }
}

4.0 Use Case 3

4.1 Developing a Simple Mock Route

Here, we will develop a simple route with a mock component.The Mock component provides a powerful declarative testing mechanism, which is similar to jMock in that it allows declarative expectations to be created on any Mock endpoint before a test begins. Then, the test is run, which typically fires messages to one or more endpoints, and finally, the expectations can be asserted in a test case to ensure the system worked as expected. 

package com.learncamel.direct;

import org.apache.camel.builder.RouteBuilder;

public class SampleMockRoute extends RouteBuilder {
    public void configure() throws Exception {

        from("direct:sampleInput")
                .log("Received Message is ${body} and Headers are ${headers}")
                .to("mock:output");
    }
}

4.2 Writing Test Case for the Route

You will see that the below test case will verify that the data received is equal to the expected data.

package com.learncamel.direct;

import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import java.io.File;

public class SampleMockRouteTest extends CamelTestSupport {
    @Override
    public RoutesBuilder createRouteBuilder() throws Exception {
        return new SampleMockRoute();
    }

    @Test
    public void sampleMockTest() throws InterruptedException {

        String expected="Hello";
        /**
         * Producer Template.
         */

        MockEndpoint mock = getMockEndpoint("mock:output");
        mock.expectedBodiesReceived(expected);
        String input="Hello";
        template.sendBody("direct:sampleInput",input );
        assertMockEndpointsSatisfied();


    }
}

5.0 POM Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.learncamel</groupId>
    <artifactId>learncamel-simple-file</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.19.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <version>2.19.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
    </dependencies>
</project>

Now, you know how to write unit test cases for Camel routes.

unit test Apache Camel Test case

Opinions expressed by DZone contributors are their own.

Related

  • Any Version of the Test Pyramid Is a Misconception – Don’t Use Anyone
  • Tooling Guide for Getting Started With Apache Camel in 2021
  • Building an Image Classification Pipeline With Apache Camel and Deep Java Library (DJL)
  • Effective Engineering Feedback: Software Testing

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook