尝试找出如何在 Spring Integration 工作流程中最好地对 http:outbound-gateway
进行单元测试。
这是我们的网关的样子:
<int-http:outbound-gateway id="gateway"
request-channel="registrationQueue"
message-converters="jsonMessageConverter"
url-expression="@urlGenerator.resolve()"
http-method="POST"
expected-response-type="javax.ws.rs.core.Response"
reply-channel="nullChannel"
error-handler="httpResponseErrorHandler"/>
具体来说,我们想要..
- 断言正在发送的对象的序列化;
消息转换器
是否正确处理来自请求 channel
的消息? - 验证第三方服务的响应处理;给出各种响应(预期和意外)和错误(内部和外部)时的行为是什么?
我们有许多单元测试,可以模拟端点并断言集成工作流程的步骤按预期运行。类似于以下内容:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-config.xml"})
public class FileRegistrationWorkflowTest {
...
@Autowired
private MessageChannel fileFoundChannel;
@Autowired
private QueueChannel testRegistrationQueue;
...
@Test
public void shouldQueueRegistrationForFileWithEntityId() {
// Given
mockFileLookupService(FILE_ID, FILENAME_WITH_ENTITY_ID);
// When
fileFoundChannel.send(MessageBuilder.withPayload(FILE_ID).build());
// Then
Message<?> message = testRegistrationQueue.receive();
assertThat(message, hasPayload(expected));
}
}
这种测试方法非常适合工作流程中的步骤。我们的麻烦是测试端点网关..
- 我们无法模拟
http:outbound-gateway
,那么我们就不会对其进行测试。 - 我们不想部署真正的 HTTP 服务来进行交互,这更像是一个集成测试。
- 第 3 方服务仅由
url 表达式
解析,因此没有可模拟的 Spring bean。
也许我们可以拦截Spring尝试发送的HTTP请求?
最佳答案
在 framework tests我们使用 DirectFieldAccessor 将端点的 RestTemplate 替换为模拟(实际上是 stub )。但是,这不会测试转换器。
您可以变得更加复杂,可以测试真正的RestTemplate
;只需获取对其的引用(使用 SI TestUtils.getPropertyValue()
或 DirectFieldAccessor
)并按照 Spring Framework documentation 中的讨论进行配置。 .
您可以使用 bean 名称 endpointId.handler
获取对处理程序的引用。
关于java - Spring集成单元测试http :outbound-gateway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961588/