Unit Testing for Camel Rest DSL and Spring Boot

Hopefully by now, you know how to write your first Rest DSL Camel Route using Spring Boot.  If not, check this post first. Now that you have your route written, it’s time to write a unit test for it.  Many people find Apache Camel unit testing a big struggle to figure out.  Luckily, when using Spring Boot with the Apache Camel Rest DSL testing, a Rest Route isn’t too difficult.

First you will setup your test class:

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleCamelApplicationTest {

Now that your test class is set up you need to add any variables needed in all the test methods. Since this unit test will be testing a Rest service, we need to inject the TestRestTemplate into the testing class:

import org.springframework.boot.test.web.client.TestRestTemplate;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleCamelApplicationTest {
   private TestRestTemplate restTemplate;

Finally, you write your test class. Testing with Spring Boot allows you to essentially make a request to your Rest service and validate that you are receiving the response you expect.

public void sayHelloTest() {
   // Call the REST API
   ResponseEntity<String> response = restTemplate.getForEntity("/camel/hello", String.class);
   String s = response.getBody();
   assertThat(s.equals("Hello World"));

Don’t forget to come out to my workshop with Claus Ibsen at Red Hat Summit to learn more about the Rest DSL; how to test this route; deploying to Red Hat OpenShift; and how to use 3scale by Red Hat to manage your APIs.

Download and learn more about Red Hat JBoss Fuse, an innovative modular, cloud-ready architecture, powerful management and automation, and world class developer productivity. It is Java™ EE 7 certified and features powerful, enterprise-grade features such as high availability clustering, distributed caching, messaging, transactions, and a full web services stack.