ApacheCamel使用JSON路径表达式测试并断言JSON主体字段值



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

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

注意:我知道还有其他方法,通过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");
}
};
}
}

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

最新更新