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

时间:2019-08-08 15:43:29

标签: spring spring-integration spring-test spring-integration-dsl

用于测试以下IntegrationFlow

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

我写了一个配置类:

@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();
    }
}

和一个测试课程:

@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)接收消息,就像发送的一样。有没有在测试中使用模拟处理程序的解决方案?

1 个答案:

答案 0 :(得分:1)

您需要对handle()方法存根。

类似的东西:

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

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