0

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");
            }
        };
    }

}
Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106

1 Answers1

1

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);
wp78de
  • 18,207
  • 7
  • 43
  • 71
  • It's useful to know (that's why I upvoted) how to evaluate the expression to get the field value but what I was searching for, setting the mock to expect the value of a field of the json body and still I can't see a way to do so. I was wondering if there was such a functionality. – Levent Divilioglu Dec 09 '20 at 11:00
  • @LeventDivilioglu not sure, would it be helpful to make the assert inside of `getMockEndpoint()`? – wp78de Dec 09 '20 at 15:50