Testing camel routes - java

I have multiple routes classes defined in my project under com.comp.myapp.routes.
For testing these I am mocking the end route and checking/comparing delivery received.
Say for example I have below routes:
public class MyRoute1 extends RouteBuilder {
public void configure() throws Exception {
//Route_1 code
}
}
public class MyRoute2 extends RouteBuilder {
public void configure() throws Exception {
//Route_2 code
}
}
....
...//some route impl
..
public class MyRouteN extends RouteBuilder {
public void configure() throws Exception {
//Route_N code
}
}
Now for all these routes the test case that I wrote seems same.
First mock it.
Mock for MyRoute1:
public class MyRoute1_Mock extends RouteBuilder {
public void configure() throws Exception {
from("direct:sampleInput")
.log("Received Message is ${body} and Headers are ${headers}")
.to("mock:output");
}
}
Test for MyRoute1:
public class MyRoute1_Test extends CamelTestSupport {
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new MyRoute1_Mock();
}
#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();
}
}
Now to make unit test for other classes just copy and paste the above code with different name say MyRoute2_Test , MyRoute3_Test , ...MyRouteN_Test.
So what did it actually tested?
It's just written for the purpose of writing test case.
It actually just checks/tests if mock library and camel-test library work or not Not our code works or not?
How should it actually be done?

You want to test your Camel routes but in the test you mock them away. So yes, you are testing your route mock instead of the real route.
To test your real routes:
Send a message to your real routes from endpoint
If this is not easy, mock your from endpoint (not the entire route!) by replacing it with a direct endpoint. This is quite easy with adviceWith
The test message is going through your route
Assert that any to endpoint receives the correct message by mocking these endpoints too. Again, use adviceWith for that. And Camel Mock of course
You can get the received messages (Exchanges) from a Camel Mock to do in depth assertions
If you got the happy test, start to write negative tests by injecting errors in your route. adviceWith can help here too
... and so on
If you are completely new to Camel route tests, get Camel in Action 2nd edition. It explains all mentioned testing aspects for Camel applications on 65 pages. And of course it also takes you on a complete ride through the Camel universe on much more pages.
By the way: if testing your routes is hard, they are too complex. Start to divide your routes so that they are easily testable.

The route you show doesn't really do anything to the messages traversing it, so testing that the same text you sent in one end comes out the other is all there is to test.
For routes with more data transformation and processing, you could test the output data types, that processors were called when needed, you could mock in throwing of exceptions, etc. What you have above is a good start on that.

Explained in-line,Hope this helps you understand significance of Mock in Unit Test:
public void sampleMockTest() throws InterruptedException {
String expected="Hello";
MockEndpoint mock = getMockEndpoint("mock:output");//Mocking endpoint
mock.expectedBodiesReceived(expected); //Setting expected output to mocked endpoint
String input="Hello";
template.sendBody("direct:sampleInput",input );//triggering route execution by sending input to route
assertMockEndpointsSatisfied(); //Verifies if input is equal to output
}
If your endpoint is Rest service you can make use of "TestRestTemplate" instead of Mocking it and Test like below:
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 {
}
import org.springframework.boot.test.web.client.TestRestTemplate;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleCamelApplicationTest {
#Autowired
private TestRestTemplate restTemplate;
}
#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"));
}

Related

Camel: How to mock a route with two endpoints

I'm new to Camel and I need to understand how to unit test my route that has two endpoints. The first endpoints gets a user ID and uses that for the second endpoint.
public RouteBuilder routeBuilder() {
return new RouteBuilder() {
#Override
public void configure() throws HttpOperationFailedException {
this.from(MyServiceConstant.ROUTE)
.setHeader(...)
.setHeader(...)
.to(MyConstants.THE_FIRST_ROUTE)
.setHeader(...)
.setHeader(...)
.process(...)
.setProperty(...)
.to(MyConstants.THE_SECOND_ROUTE)
}
};
}
So I have to mock both the MyConstants.THE_FIRST_ROUTE and MyConstants.THE_SECOND_ROUTE in my Test class. I did that but am not sure how to write the test. All I'm doing is hitting the second endpoint but don't know how to trigger the first.
#Produce(uri = MyServiceConstant.ROUTE)
private MyService myService;
#EndpointInject(uri = "mock:" + MyConstants.THE_FIRST_ROUTE)
private MockEndpoint mockFirstService;
#EndpointInject(uri = ""mock:" + MyConstants.THE_SECOND_ROUTE)
private MockEndpoint mockSecondService;
#Test
#DirtiesContext
public void getDetails()throws Exception {
// **The missing part**: Is this the right way to call my first service?
this.mockFirstService.setUserId("123456");
// this returns a JSON that I'll compare the service response to
this.mockSecondService.returnReplyBody(...PATH to JSON file);
UserDetail userDetailsInfo = this.myService.getUserDetails(...args)
// all of my assertions
assertEquals("First name", userDetailsInfo.getFirstName());
MockEndpoint.assertIsSatisfied();
}
I got some time today to quickly hack around some demo code, with Camel Spring boot archetype. Here we go. My route produces messages from a timer component. Explicit delivery to an endpoint is not used.
//Route Definition - myBean::saySomething() always returns String "Hello World"
#Component
public class MySpringBootRouter extends RouteBuilder {
#Override
public void configure() {
from("timer:hello?period={{timer.period}}").routeId("hello_route")
.transform().method("myBean", "saySomething")
.to("log:foo")
.setHeader("test_header",constant("test"))
.to("log:bar");
}
}
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest
public class MySpringBootRouterTest {
#Autowired
SpringCamelContext defaultContext;
#EndpointInject("mock:foo")
private MockEndpoint mockFoo;
#EndpointInject("mock:bar")
private MockEndpoint mockBar;
#Test
#DirtiesContext
public void getDetails() throws Exception {
assertNotNull(defaultContext);
mockBar.expectedHeaderReceived("test_header", "test");
mockBar.expectedMinimumMessageCount(5);
MockEndpoint.setAssertPeriod(defaultContext, 5_000L);
MockEndpoint.assertIsSatisfied(mockFoo, mockBar);
mockFoo.getExchanges().stream().forEach( exchange -> assertEquals(exchange.getIn().getBody(),"Hello World"));
//This works too
//mockBar.assertIsSatisfied();
//mockFoo.assertIsSatisfied();
}
#Before
public void attachTestProbes() throws Exception {
//This is Camel 3.0 API with RouteReifier
RouteReifier.adviceWith(defaultContext.getRouteDefinition("hello_route"), defaultContext, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
//Hook into the current route, intercept log endpoints and reroute them to mock
interceptSendToEndpoint("log:foo").to("mock:foo");
interceptSendToEndpoint("log:bar").to("mock:bar");
}
});
}
}
Warning to visitors from future: The test case here demonstrates how to intercept log: endpoints with mock: and set expectations on them. The test case may not be testing anything worthwhile.
Here is a link to the Unit Test cases for the Mock component. It shows how to implement tests with mock: endpoints and CamelTestSupport. #Roman Vottner is completely right in his comment.
This test case may be of specific interest to you since it shows how to swap an smtp: endpoint with a mock: endpoint. Additionally, here is official documentation on how to mock existing endpoints (To use them like test probes).
Caveat: Please bear in mind that Camel 3.0 API is quite different from Camel 2.x API, in this region. Good luck!

Exposing endpoint URL in tests

Let's go straight to the problem:
I want to test a method that wants URL of Rest endpoint as a parameter. That method is using RestTemplate internally to send a request to that URL, so it needs to be full URL, for example http://localhost:8080/rest. Because of that I also have no way to mock RestTemplate.
I wanted to create simple #RestController but it seems that Spring is not creating endpoint when running tests.
I've tried creating MockMvc but it's not what I want. I have no way of getting the IP and port of MockMvc's created endpoint because no actual endpoint is created.
So, what I want is to make my #RestController accessible in tests by sending requests to URL, for example: http://localhost:8080/rest.
It's my first time creating a test like that, I will be grateful for your help. I was searching for an answer but I couldn't find a solution for my problem.
Edit:
Here's some code:
Unfortunately I can't post all the code but what I'm posting should be enough:
I have my endpoint like(names changed):
#RestController
public class EndpointController {
#RequestMapping(value = "/rest", method = RequestMethod.POST)
public List<Output> doSomething(#RequestBody Input[] requestList){
...
}
}
It's endpoint only for testing, it mimics the real endpoint. Then during my test I'm creating an object like:
new EndpointClient("http://localhost:8080/rest")
which has inside something like this:
ResponseEntity<Output[]> responseEntity = restTemplate.exchange(endpointURL,HttpMethod.POST, httpEntity, Output[].class);
Method having restTemplate request isn't called directly during testing(it's called by another method).
So I need to pass that URL to the Client object.
If you want to test your web application, checkout the Getting Started: Testing the Web Layer documentation.
Spring Boot is providing some useful annotations like #SpringBootTest, #AutoConfigureMockMvc, ...
See also the TestRestTemplate, which can be autowired to your WebMvcTest.
edit:
An example, copied from the documentation mentioned above:
package hello;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate;
#Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Hello World");
}
}
I found a solution for my problem.
I did it with WireMock: http://wiremock.org/
First I had to create Transformer for my request, so the response depends on request, something like:
public class MyTransformer extends ResponseTransformer {
#Override
public Response transform(final Request request,
final Response response,
final FileSource fileSource,
final Parameters parameters){
HttpHeaders headers = new HttpHeaders(new HttpHeader("Content-Type", "application/json"));
if(request.getUrl().contains("/rest")){
...
return Response.Builder.like(response).but().body(...).headers(headers).build();
} else
return Response.Builder.like(response).but().status(404).headers(headers).build();
}
#Override
public String getName() {
return "swapper";
}
}
In my test I needed to put
WireMockServer server = new WireMockServer(wireMockConfig().port(3665).extensions("package.name.endpoint.MyTransformer"));
server.stubFor(post("/rest"));
It created exactly what I wanted. Code above is extremely simple, probably not that good and needs work but it shows the basics.

Camel adviceWith for ExceptionHandler

I need to test my Camel Exception handler:
#Configuration
public class RouteConfiguration extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(HttpOperationFailedException.class).
handled(true).
log("HttpOperationFailedException: ${exception}").
onExceptionOccurred(myRestExceptionProcessor).id("myRestExceptionProcessor").end();
from("direct:myPrettyRoute").routeId("myPrettyRoute");//lots of routing here
}
}
I'm trying to add adviceWith after myRestExceptionProcessor, but can't find a way.
public class MyExceptionRoutingTest {
#Autowired
private CamelContext context;
#Before
public void before() throws Exception {
if (ServiceStatus.Stopped.equals(context.getStatus())) {
log.info("prepare mocks endpoint");
List<OnExceptionDefinition> ed = context.getErrorHandlerBuilder().getErrorHandlers(context.getRoutes().get(0).getRouteContext());
//FAILS, because context.getRoutes() is empty at the moment
//even if it wasn't, getErrorHandlerBuilder() is deprecated
}
}
}
I need to add something like this for the exceptionHandler definition:
.adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveById("myExceptionProcessor").after().to(myResultEndpoint).id("myResponseEndpoint");
}
});
Is it possible?
I don't fully understand if you want to test your error handler (onException block) or just your myRestExceptionProcessor, but from a Camel perspective these are two kinds of tests:
Routing-Tests to test your routing logic and make sure that messages are correctly routed under various conditions that could happen in the route. This is the kind of tests you write with the Camel Testkit (that offers adviceWith and much more).
Classic unit tests to test an isolated Bean, Processor or anything else that is used in the route to implement business logic. This kind of test is done with JUnit, TestNG or other classic unit test frameworks, it has nothing to do with Camel. Do not try to test such components with Camel Route tests since it is much more complicated than in a unit test!
So, if you want to test your routing when an error occurs you throw the needed error in your route test to trigger the error handler. If you use a dependency injection framework like Spring this is easy since you can inject a test Bean that throws an error instead of a real Bean used in the route.
To add a Mock endpoint at the end of a route, use adviceWith
.adviceWith(camelContext, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveAddLast().to("mock:error");
}
}
Hope this helps a bit. Feel free to extend your question to elaborate your problem a bit more.
I've solved the trick as follows, without changing the route:
//entry point of the route is invoked here
Exchange send = myProducer.withBody("body is here").send();
HttpOperationFailedException exception = send.getException(HttpOperationFailedException.class);
String responseBody = exception.getResponseBody();
//recieved result and made assertions
assert responseBody != null; // any other assertions

junit test case for spring MVC

we are developing an application using spring mvc framework. I have given all the classes below, please suggest how to write a junit test case for the below scenario.
I want to write a junit test case for the validateAccountInformation(requestDTO) method which is called in validateAccount(..) method of LPAValidator.java class. Below is my junit test case followed by the java classes. Actual call goes from the LPAController.java as shown in the below code.
LPAControllerTest.java
#Test(groups = "manual")
public void submitRequestForLPAAccountTest()
{
// businessCalendar.nextBusinessDay(
// LocalDateHelper.today(), LPAConstants.TWENTY_BUSSINESS_DAYS)
//i want to write the test case for the above commented logic,
//if business days is not equal to twenty days, test should fail.
}
LPAController.java
#RequestMapping(value = "/lpa/{accNumber}/spread, method = RequestMethod.GET)
public #ResponseBody LPAResponseDTO accountSearch(#RequestBody final LPARequestDTO clientrequestBody,
#PathVariable final String accNumber, final HttpServletResponse response)
{
//some logic goes here
final LPAAccountResponse domainResponse = service.submitRequestForLPAAccount(requestBody);
}
LPAServiceImpl.java
#PermitAll
#NonTransactional
public LPAResponse submitRequestForLPAAccount(final LPARequest requestDTO)
{
return lpaRepository.submitRequestForLPAAccount(requestDTO));
}
LPARepository.java
#PermitAll
#NonTransactional
public LPAResponse submitRequestForLPAAccount(final LPARequest requestDTO)
{
//some logic
lpaValidator.validateAccount(requestDTO);
//some logic
}
LPAValidator.java -- java class for validations
#component
class LPAValidator{
#Inject
private BusinessCalendar businessCalendar;
void validateAccount(final LPARequest requestDTO) throws Exception {
try {
validateAccountInformation(requestDTO);
} catch(Exception e){
}
}
private void validateAccountInformation(final LPARequest requestDTO) throws Exception{
final accDate lpaAccDate = requestDTO.getLPADate();
final LocalDate twentyBussinessDays = businessCalendar.nextBusinessDay(
LocalDateHelper.today(), LPAConstants.TWENTY_BUSSINESS_DAYS); //i want to write
//test case for this line of code, if business days given is more than twenty test should fail.
//some logic here
}
Please suggest what needs to be added in LPAControllerTest.java to test the nextBusinessDay(..) as discussed above.
You're trying to write an integration test in which your controller is called, which then calls all the subclasses until the validator is triggered. That is not a traditional 'unit test'.
A traditional unit test would just test the validator straight up, and nothing more.
Nevertheless, when writing an integration test, spring documentation to the rescue
In short, it'll require you to create an applicationcontext with all the necessary scaffolding, and then use a mockMvc call to do a GET on the created application.
If you want to test the validator, use simple mocking framework:
See [http://mockito.org]
Gives you something like this:
#Mock BusinessCalendar businessCalendarMock;
#Mock LPARequest mockRequest;
#Mock accDate mockDate;
#Mock LocalDate mockLocalDate;
#InjectMocks LPAValidator lpaValidator = new LPAValidator();
#Test public void testValidateAccount() {
when(mockRequest.getLPAdate()).thenReturn(mockDate);
when(businessCalendar.nextBusinessDay(LocalDateHelper.today(),LPAConstants.TWENTY_BUSSINESS_DAYS).thenReturn(mockLocalDate);
// continue your test from here
lpaValidator.validateAccount( mockRequest);
verify(businessCalendar).nextBusinessDay(LocalDateHelper.today(),LPAConstants.TWENTY_BUSSINESS_DAYS);
// although if the use of mockLocalDate is integral to your code, it'll probably show before and no verify is necessary;

Unit testing jersey Restful Services

I'm new to unit testing and I want to test some jersey services in a project. We are using Junit. Please guide me to write test cases in better way.
CODE:
#GET
#Path("/getProducts/{companyID}/{companyName}/{date}")
#Produces(MediaType.APPLICATION_JSON)
public Object getProducts(#PathParam("companyID") final int companyID,
#PathParam("date") final String date, #PathParam("companyName") final String companyName)
throws IOException {
return productService.getProducts(companyID, companyName, date);
}
Above mentioned service is working fine and I want to write junit test case to test above mentioned method. Above method will retrieve list of products (List<Product>) in JSON format. I would like to write test case to check response status and json format.
NOTE: We are using Jersey 1.17.1 version.
Help would be appreciated :)
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (already mentioned in other answer - see here documentation for version 1.17 here: https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).
I find the REST-Assured more interesting and powerful, but Jersey Test Framework is very easy to use too. In REST-Assured to write a test case "to check response status and json format" you could write the following test (very much like you do in jUnit):
package com.example.rest;
import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;
import org.junit.Before;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class Products{
#Before
public void setUp(){
RestAssured.basePath = "http://localhost:8080";
}
#Test
public void testGetProducts(){
expect().statusCode(200).contentType(ContentType.JSON).when()
.get("/getProducts/companyid/companyname/12345088723");
}
}
This should do the trick for you... you can verify JSON specific elements also very easily and many other details. For instructions on more features you can check the very good guide from REST-Assured (https://code.google.com/p/rest-assured/wiki/Usage). Another good tutorial is this one http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/.
HTH.
Just ignore the annotations and write a normal unit test that passes the required parameters. The return I thought would usually be of type "javax.ws.rs.core.Response" ... There is a getEntity() method on that can be used. Using a Mock object framework like Mockito could be helpful in this case too.
Are you familiar with Chapter 26. Jersey Test Framework?
public class SimpleTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}

Categories

Resources