测试场景下如何让SourcePollingChannelAdapter先调用BooksHandler再输出
问题解决:让SourcePollingChannelAdapter触发BooksHandler后再发送到Kafka通道
你遇到的核心问题是:测试中直接修改了booksPollingSource的输出通道为Kafka通道,跳过了原集成流里BooksHandler的处理环节。原集成流的逻辑是适配器轮询取数 → 经过BooksHandler处理 → 发送到Kafka通道,而你当前的测试代码直接把适配器输出指向了Kafka,自然不会触发Handler。
以下是几种实用的解决方式:
方式一:用中间通道串联Handler与目标通道
创建一个临时中间通道,让消息先经过BooksHandler处理,再转发到Kafka通道:
@Test public void testBooks() { // 创建中间通道,绑定BooksHandler作为订阅者 DirectChannel intermediateChannel = new DirectChannel(); intermediateChannel.subscribe(booksHandler); // 配置BooksHandler处理后的消息输出到Kafka通道 booksHandler.setOutputChannel(syncBooksMessageChannel); // 设置适配器的输出为中间通道 booksPollingSource.setOutputChannel(intermediateChannel); booksPollingSource.setAutoStartup(false); booksPollingSource.start(); // 这里可添加触发轮询、等待消息处理完成的逻辑,比如Thread.sleep或CountDownLatch }
方式二:复用原集成流的完整逻辑(推荐)
原集成流已经定义了完整的处理链,测试时无需手动修改适配器的输出通道,直接触发适配器即可:
@Autowired @Qualifier(BOOKS_POLLING_ADAPTER_ID) protected SourcePollingChannelAdapter booksPollingSource; @Test public void testBooks() { booksPollingSource.setAutoStartup(true); booksPollingSource.start(); // 等待轮询触发,验证BooksHandler的执行痕迹及Kafka消息 }
如果需要隔离Kafka(比如用测试通道替代),可以用@MockBean替换syncBooksMessageChannel Bean,原流程会自动将Handler处理后的消息发送到你模拟的测试通道中。
方式三:用MessageHandlerChain构建处理链
通过MessageHandlerChain将BooksHandler和通道转发逻辑串联,直接设置为适配器的输出处理器:
@Test public void testBooks() { MessageHandlerChain handlerChain = new MessageHandlerChain(); // 先执行BooksHandler,再将消息转发到Kafka通道 handlerChain.setHandlers(Arrays.asList( booksHandler, new MessageChannelForwardingHandler(syncBooksMessageChannel) )); booksPollingSource.setOutputHandler(handlerChain); booksPollingSource.setAutoStartup(false); booksPollingSource.start(); }
MessageChannelForwardingHandler是Spring Integration内置类,负责将消息转发到指定通道。
内容的提问来源于stack exchange,提问作者Sajad
相关产品推荐
相关产品推荐

