Citrus Framework:Java DSL能否模拟SOAP服务器发送MTOM附件?
在Citrus Framework中用Java DSL实现SOAP服务器返回MTOM附件响应
好问题!我之前在模拟SOAP后端时也碰到过这个情况——确实客户端的soap().client()有现成的attachment()方法,但服务器端的Java DSL接口看起来没有直接暴露这个方法。不过完全不用切换到XML DSL,Java DSL可以通过操作底层的SoapMessage对象来实现MTOM附件的返回,具体步骤如下:
1. 先确保SOAP服务器启用MTOM
首先要在你的服务器配置中开启MTOM支持,如果是XML配置的话,给<citrus-ws:server>添加mtom-enabled="true"属性:
<citrus-ws:server id="backendSimulationServer" port="8080" auto-start="true" interceptors="serverInterceptors" timeout="5000" mtom-enabled="true"/>
如果是用Java配置类定义服务器,对应调用mtomEnabled(true):
@Bean public SoapServer backendSimulationServer() { return soapServer() .port(8080) .autoStart(true) .interceptors(serverInterceptors()) .timeout(5000) .mtomEnabled(true) .build(); }
2. 在Java DSL的send动作中添加MTOM附件
在发送响应的步骤里,你可以通过message()回调方法直接操作底层的SoapMessage对象,手动添加MTOM附件。示例代码如下:
runner.send(action -> action.endpoint("backendSimulationServer") .name("search-response") .payload(new ClassPathResource("testfiles/search-response.xml")) .message(message -> { // 转换为SoapMessage对象以便操作附件 SoapMessage soapMessage = (SoapMessage) message; // 创建附件的DataHandler(这里以本地PDF文件为例) DataHandler attachmentHandler = new DataHandler(new FileDataSource("testfiles/attachment.pdf")); // 添加附件,指定唯一的Content-ID(要和响应XML里的xop:Include引用对应) soapMessage.addAttachment("attachment-cid", attachmentHandler); // 可选:显式设置附件的Content-Type soapMessage.getAttachment("attachment-cid").setContentType("application/pdf"); }) );
3. 确保响应XML符合MTOM规范
别忘了在你的search-response.xml中添加对附件的引用,使用xop:Include标签指向刚才设置的Content-ID:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xop="http://www.w3.org/2004/08/xop/include"> <soap:Body> <searchResult> <document> <xop:Include href="cid:attachment-cid"/> </document> </searchResult> </soap:Body> </soap:Envelope>
额外说明
如果你的测试中有多个响应需要添加MTOM附件,也可以封装一个自定义的消息处理器或者拦截器,统一处理附件逻辑,避免重复代码。但针对单个响应的场景,上面的直接操作SoapMessage的方式就足够简洁了。
完全不需要切换到XML DSL,Java DSL就能搞定这个需求,亲测有效!
内容的提问来源于stack exchange,提问作者burki
相关产品推荐
相关产品推荐

