ApacheCamel使用json路径表达式测试并Assertjson主体字段值

wsewodh2  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(364)

我试图检查body的字段值,它是一个json字符串,带有 JsonPathExpression .
在下面的示例中 JsonPathExpression 检查根json对象是否具有名为“”的字段 type ". 我想要达到的是,用 JsonPathExpression 如果字段值为“ type “等于某个字符串值。
注意:我知道还有其他方法,通过 MockEndpoint#getReceivedExchanges 但我不想使用它,因为它超出了Assert范围。
这是我的考试班;

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

}
ryoqjall

ryoqjall1#

按照克劳斯的建议,我们可以从camel自己的jsonpath单元测试中得到启发:

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

相关问题