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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Jitendra Bafna user avatar by
Jitendra Bafna
CORE ·
Jan. 01, 18 · Tutorial
Like (5)
Save
Tweet
Share
71.43K 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.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • 19 Most Common OpenSSL Commands for 2023
  • Using Swagger for Creating a PingFederate Admin API Java Wrapper
  • How To Best Use Java Records as DTOs in Spring Boot 3

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: