Java Apache Camel使用JSON路径表达式测试并断言JSON正文字段值
我试图检查body的字段值,它是一个JSON字符串,带有Java Apache Camel使用JSON路径表达式测试并断言JSON正文字段值,java,apache-camel,jsonpath,json-path-expression,camel-test,Java,Apache Camel,Jsonpath,Json Path Expression,Camel Test,我试图检查body的字段值,它是一个JSON字符串,带有JsonPathExpression 在下面的示例中,JsonPathExpression检查根JSON对象是否具有名为“type”的字段。我想要实现的是,如果字段值“type”等于某个字符串值,则使用JsonPathExpression进行断言 注意:我知道还有其他方法,通过MockEndpoint\getReceivedExchanges提取消息体,但我不想使用它,因为它超出了断言范围 这是我的测试课 import org.apache
JsonPathExpression
在下面的示例中,JsonPathExpression
检查根JSON对象是否具有名为“type
”的字段。我想要实现的是,如果字段值“type
”等于某个字符串值,则使用JsonPathExpression
进行断言
注意:我知道还有其他方法,通过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");
}
};
}
}
按照克劳斯的建议,我们可以从骆驼自己身上得到启发:
您可以尝试使用此计算器为其构建语法:@ClausIbsen是否有方法使用json路径表达式检索json正文的值并检查它?@ClausIbsen Like mock.message(0.body()。???(新的JsonPathExpression().equalsTo();尝试查看camel jsonpath源代码以了解其自身的单元测试。这很有用(这就是我投赞成票的原因)如何计算表达式以获取字段值,但我正在搜索的是,将mock设置为期望json正文的字段值,但我仍然找不到这样做的方法。我想知道是否有这样的功能。@LeventDivilioglu不确定,在
getMockEndpoint()
中进行断言是否有帮助?
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);