Skip to main content Skip to complementary content

Unit testing of Routes

Unit testing is an essential part of any professional software development process. This section will show you how Routes can be unit tested using the Apache Camel Testing framework.

Creating a Route

To show an example of Unit testing, you will create a Route first. This Route reads a file from the specific directory and filters the messages of the file.

Procedure

  1. Place the following components from the Palette onto the design workspace:
    • a cFile,
    • a cConvertBodyTo,
    • a cMessageFilter,
    • and a cMessagingEndpoint.
    Screenshot of the Job in the design workspace.
  2. Label the components for better identification of their roles. Link the cMessageFilter component and the cMessagingEndpoint component using the Row > filter connection. Link the other components as shown above using the Row > Route connection.
  3. Double-click the cFile component to open its Basic settings view in the Component tab and configure it as shown below to read files from a local file system.
    Basic settings view.
  4. Double-click the cConvertBodyTo component to open its Basic settings view in the Component tab and configure it as shown below to convert the message body of each file into String type.
    Basic settings view.
  5. Double-click the cMessageFilter component to open its Basic settings view in the Component tab and configure it as shown below to filter the message body based on the expression:
    ${body} contains 'bar'
    Basic settings view.
  6. Double-click the cMessagingEndpoint component to open its Basic settings view in the Component tab and configure it as shown below to log the output of the Route.
    Basic settings view.
  7. In the Run view, click the Run button to launch the execution of your Route. The data that matches the filtering criterion is displayed in the console.
    Screenshot of the console results after successfully running the Job.

Results

For more information on how to create a Route, see Creating a Route.

Publishing the Route to the Artifact repository

Procedure

  1. Right-click the Route in the Repository tree view and select Publish in the context menu.
    The Publish into Artifact Repository wizard opens.
  2. Keep the default settings and click Finish to publish the Route into the Artifact repository.
    Publish into Artifact Repository wizard.

Results

Your item is available as an artifact in the repository.

For more information on how to publish a Route, see Publishing to an artifact repository.

Creating a Maven project for unit test

Unit tests will be put in a separate project.

You need to switch to the Java perspective and create a simple maven-based project.

Procedure

  1. Right-click the blank area in the Package Explorer and select New > Project... in the context menu.
  2. The New Project wizard opens. Select Maven Project under the Maven node and click Next.
    New Project wizard.
  3. In the Select project name and location view, the Use default Workspace location option is selected. Keep it and click Next.
    New Maven Project wizard.
  4. In the Select an Archetype view, the GroupId org.apache.maven.archetypes and ArtifactId maven-archetype-quickstart are selected. Keep the default settings and click Next.
    New Maven Project wizard.
  5. In the Specify Archetype parameters view, enter org.talend in the Group Id field and route-unit-test in the Artifact Id field. Click Finish. The project appears in the Package Explorer.
    New Maven Project wizard.
  6. Double-click the pom.xml file under the newly created project node to open it in the design workspace and edit it as shown below.
    <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>org.talend</groupId>
        <artifactId>route-unit-test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-test</artifactId>
                <version>2.9.1</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-jdk14</artifactId>
                <version>1.6.1</version>
            </dependency>
            <dependency>
                <groupId>org.talend.camel</groupId>
                <artifactId>systemRoutines</artifactId>
                <version>1.0.0</version>
            </dependency>
            <dependency>
                <groupId>org.talend.camel</groupId>
                <artifactId>userRoutines</artifactId>
                <version>1.0.0</version>
            </dependency>
            <dependency>
                <groupId>org.example</groupId>
                <artifactId>SimpleRoute</artifactId>
                <version>0.2.0-SNAPSHOT</version>
                <type>jar</type>
            </dependency>
        </dependencies>
        <repositories>
            <repository>
                <id>repo-snapshot</id>
                <name>Snapshots bundles</name>
                <url>http://tadmin:tadmin@localhost:8082/archiva/repository/repo-snapshot/</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
    </project>

    As is shown above, the Maven dependencies are Junit and Camel unit testing framework, Utility JAR files required for Talend ESB Route, and Route JAR files published from Talend Studio.

    In this use case, you will use the Route in Talend Artifact Repository directly, so it needs to be added into the pom.xml file as a repository. The username and password is put in the repository URL for simplicity. You can also specify it in your ${Maven_HOME}/conf/settings.xml.

  7. Save your pom.xml file.

Publishing utility JAR files to local Maven repository

Start a command line console to deploy the utility JAR files into your local Maven repository.

Procedure

  1. Execute following command to deploy the system routines: mvn install:install-file -DgroupId=org.talend.camel -DartifactId=systemRoutines -Dversion=1.0.0 -Dfile=./src/ext/systemRoutines.jar -Dpackaging=jar -DgeneratePom=true
  2. Execute following command to deploy the user routines: mvn install:install-file -DgroupId=org.talend.camel -DartifactId=userRoutines -Dversion=1.0.0 -Dfile=./src/ext/userRoutines.jar -Dpackaging=jar -DgeneratePom=true

Results

You have all the necessary dependencies to do unit tests.

Writing and running a Junit test

Procedure

  1. Right-click the Maven project route-unit-test in the Package Explorer and select New > JUnit Test Case in the context menu.
    New JUnit Test Case wizard.
    The New JUnit Test Case wizard opens.
  2. Select New JUnit 3 test and enter RouteTestSample as the name of your test class. Click Finish.
  3. The test class opens in the design workspace. Write the test as follows.
    package org.talend.test;
    
    import java.util.Map;
    
    import org.apache.camel.CamelContext;
    import org.apache.camel.EndpointInject;
    import org.apache.camel.Produce;
    import org.apache.camel.ProducerTemplate;
    import org.apache.camel.builder.RouteBuilder;
    import org.apache.camel.component.mock.MockEndpoint;
    import org.apache.camel.test.junit4.CamelTestSupport;
    import org.junit.Test;
    
    import esbdemos.simpleroute_0_1.SimpleRoute;
    
    public class RouteTestSample extends CamelTestSupport {
    	@EndpointInject(uri = "mock:result")
    	protected MockEndpoint resultEndpoint;
    	@Produce(uri = "direct:start")
    	protected ProducerTemplate template;
    	private RouteBuilder builder;
    
    	@Test
    	public void testSendMatchingMessage() throws Exception {
    		String expectedBody = "bar";
    		resultEndpoint.expectedBodiesReceived(expectedBody);
    		template.sendBody(expectedBody);
    		resultEndpoint.assertIsSatisfied();
    	}
    
    	@Test
    	public void testSendNotMatchingMessage() throws Exception {
    		resultEndpoint.expectedMessageCount(0);
    		template.sendBody("foo");
    		resultEndpoint.assertIsSatisfied();
    	}
    
    	@Override
    	protected CamelContext createCamelContext() throws Exception {
    		SimpleRoute route = new SimpleRoute();
    		// Setup the test aliases
    		Map<String, String> uriProperties = route.getUriMap();
    		uriProperties.put("start", "direct:start");
    		uriProperties.put("end", "mock:result");
    		route.loadCustomUriMap(uriProperties);
    		// Build the route
    		builder = route.Route(false);
    		return builder.getContext();
    	}
    
    	@Override
    	protected RouteBuilder createRouteBuilder() {
    		return builder;
    	}
    }

    As is shown above, you are going to use the Camel Test framework to test the Route, which requires to use special mock endpoints to extract results during the unit testing. However, the Route you have created does not use such mock endpoints. It uses the usual file and log components. As a solution for that, replace the file and log components with the direct:start and mock:result components. In lines 49 to 52, you can see a Map<String,String> which maps the component name to it's URI, and replaces values for start and end. By doing so, you are able to mock the components to test the Route in isolation.

  4. Click the Run Job button in the toolbar to run the test.
    JUnit tab.

    The test is successful.

Did this page help you?

If you find any issues with this page or its content – a typo, a missing step, or a technical error – please let us know!