如果在测试时在 IntegrationFlow 中使用模拟处理程序,则无法从输出通道接收消息

Cannot receive messages from the output channel if using mock handler in IntegrationFlow when testing

用于测试以下内容IntegrationFlow

IntegrationFlows.from("channel.input")
            .enrich(m -> m.header(MessageHeaders.ERROR_CHANNEL, "channel.input.error"))
            .handle("handler", "handle")
            .channel("channel.output")
            .get();

我写了一个配置class:

@Configuration
@ComponentScan
@EnableIntegration
public class ServiceFlowContext {

    @Bean(name = "handler")
    public Handler handler() {
        return Mockito.mock(Handler.class);
    }

    @Bean("channel.output")
    public QueueChannel outputChannel() {
        return new QueueChannel();
    }
}

和一个测试class:

@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
@ContextConfiguration(classes = ServiceFlowContext.class)
public class ServiceFlowTest {
    @Autowired
    private Handler handler;

    @Autowired
    @Qualifier("channel.input")
    private MessageChannel inputChannel;

    @Autowired
    @Qualifier("channel.output")
    private QueueChannel outputChannel;

    @Test
    public void shouldGetMessageInErrorChannelIfHandlerFailed() {
        Message<String> message = MessageBuilder.withPayload("empty").build();
        when(handler.handle(message)).thenReturn(message);
        inputChannel.send(message);

        Message result = outputChannel.receive(5000);
        assertThat(result).isNotNull();
    }
}

测试将在接收方法处等待 5 秒,我将得到一个空对象,导致测试失败。但是,如果我定义一个真实的对象而不是模拟对象,就像:

public static class Handler1 {
    public Message<String> handle(Message<String> message) {
        return message;
    }
}

@Bean(name = "handler")
public Handler1 handler() {
    return new Handler1();
}

然后,我可以从channel.output通道(outputChannel)接收消息,就像发送的消息一样。有没有在测试中使用模拟处理程序的解决方案?

您需要存根 handle() 方法。

类似于:

Handler handler = Mockito.mock(Handler.class);
BDDMockito.willAnswer(invocation -> invocation.getArgument(0))
    .given(handler).handle(any());
return handler;

这与您的 Handler1.handle() 相同。