Apache Camel test and assert the JSON body field value with JSON Path Expression

1.5k views Asked by At

I'm trying to check the field value of the body which is a JSON string with JsonPathExpression.

In the example below, the JsonPathExpression checks whether or not the root JSON object has the field named as "type". What I want to achieve is, to assert with the use of JsonPathExpression if the field value "type" equals to a certain String value.

Note: I know that there are other ways, by extracting the message body via MockEndpoint#getReceivedExchanges but I don't want to use that because it's out of the assertion scope.

Here is my test class;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.language.JsonPathExpression;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class MockTestWithJsonPathExpression extends CamelTestSupport {
    
    @Test
    public void testMessageContentWithJSONPathExpression() throws InterruptedException {
        MockEndpoint mock = getMockEndpoint("mock:quote");
        mock.expectedMessageCount(1);
        mock.message(0).body().matches(new JsonPathExpression("$.type")); // how to test the content of the value
        
        /* Json string;
         * 
         * {
         *     "test": "testType"
         * }
         * 
         */
        String body = "{\"type\": \"testType\"}";
        
        template.sendBody("stub:jms:topic:quote", body);
        
        assertMockEndpointsSatisfied();
    }
    
    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("stub:jms:topic:quote")
                    .to("mock:quote");
            }
        };
    }

}
1

There are 1 answers

2
wp78de On

Following Claus' suggestion, we can take inspiriation from Camel's own JsonPath unit tests:

Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody(new File("/or/mock/file.json"));

Language lan = context.resolveLanguage("jsonpath");
Expression exp = lan.createExpression("$.test");
String test = exp.evaluate(exchange, String.class);

assertNotNull(test);
assertEquals("testType", test);