Apache Camel路由条件写入文件及Spring环境下Mock响应测试相关问题
Apache Camel路由相关问题解答
问题一:条件触发文件写入的实现
你可以通过Camel内置的filter组件实现单条件的路由分支,改造后的路由示例如下:
Java DSL写法
from("amq:MyQueue") .process("jmsToHttp4") .to("http4://dummyhost:8080") // 仅当body包含Response关键词时才执行后续的文件写入操作 .filter(simple("${bodyAs(String)} contains 'Response'")) .to("file://out/MyFolder") .end();
说明
- http4组件调用完成后,响应结果会自动存入Exchange的消息body中,无需手动调用
exchange.getOut().getBody()获取再判断 - 用
bodyAs(String)做类型转换是为了避免非字符串类型的body判断异常,如果你能确定返回结果一定是字符串,直接写${body} contains 'Response'也可以
如果有多个分支判断需求,也可以换成choice()/when()的写法实现更复杂的路由逻辑。
问题二:Spring环境下Mock响应的实现
核心结论
你说的「直接将对应的响应字符串写入exchange.out.body」逻辑是成立的,不同测试场景的具体实现方式如下:
- 单元测试自定义处理器:如果仅测试自己编写的
jmsToHttp4这类自定义Processor逻辑,直接构造Exchange对象,手动给out body赋值对应响应字符串即可完成测试。 - 集成测试完整路由:如果要测试整条路由的流转逻辑,推荐用Camel Spring测试套件的Mock端点能力模拟http4返回,示例代码如下:
// 测试类上添加Mock注解,拦截所有http4端点调用 @MockEndpoints("http4:*") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:your-spring-config.xml"}) public class CamelRouteTest extends CamelSpringTestSupport { @EndpointInject("mock:http4:dummyhost:8080") private MockEndpoint mockHttpEndpoint; // 正向测试用例 @Test public void testPositiveResponse() throws Exception { // 设置Mock的http端点返回正向响应 mockHttpEndpoint.whenAnyExchangeReceived(exchange -> { exchange.getOut().setBody("Your Response positive test"); }); mockHttpEndpoint.expectedMessageCount(1); // 往路由入口发送测试消息 template.sendBody("amq:MyQueue", "test input payload"); // 断言http调用符合预期,再验证file目录下生成了对应文件即可 mockHttpEndpoint.assertIsSatisfied(); } // 负向测试用例 @Test public void testNegativeResponse() throws Exception { mockHttpEndpoint.whenAnyExchangeReceived(exchange -> { exchange.getOut().setBody("Your negative test"); }); mockHttpEndpoint.expectedMessageCount(1); template.sendBody("amq:MyQueue", "test input payload"); mockHttpEndpoint.assertIsSatisfied(); // 验证file目录下没有生成文件即可 } }
内容的提问来源于stack exchange,提问作者hingiswiss
相关产品推荐
相关产品推荐

