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; @RunWith(SpringRunner.class) @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; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class SampleCamelApplicationTest { @Autowired 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.
@Test public void sayHelloTest() { // Call the REST API ResponseEntity<String> response = restTemplate.getForEntity("/camel/hello", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); 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.
Last updated: March 18, 2024