0

我正在尝试检查正文的字段值,它是一个 JSON 字符串,带有JsonPathExpression.

在下面的示例中,JsonPathExpression检查根 JSON 对象是否具有名为“ type”的字段。我想要实现的是,使用JsonPathExpression字段值“ type”是否等于某个字符串值来断言。

注意:我知道还有其他方法,通过提取消息正文,MockEndpoint#getReceivedExchanges但我不想使用它,因为它超出了断言范围。

这是我的测试课;

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

}
4

1 回答 1

1

按照 Claus 的建议,我们可以从 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);
于 2020-12-08T04:08:59.687 回答