Reputation: 930
For testing the following IntegrationFlow
:
IntegrationFlows.from("channel.input")
.enrich(m -> m.header(MessageHeaders.ERROR_CHANNEL, "channel.input.error"))
.handle("handler", "handle")
.channel("channel.output")
.get();
I wrote a configuration 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();
}
}
and a test 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();
}
}
The test will wait at the receive method for 5 seconds and I will get a null object which causes the test failed. However, if I define a real object instead of the mock object, just as:
public static class Handler1 {
public Message<String> handle(Message<String> message) {
return message;
}
}
@Bean(name = "handler")
public Handler1 handler() {
return new Handler1();
}
then, I can receive the message from channel.output
channel (outputChannel) just as the same as what is sent. Are there any solutions to use mock handler in the test?
Upvotes: 0
Views: 357
Reputation: 174729
You need to stub the handle()
method.
Something like:
Handler handler = Mockito.mock(Handler.class);
BDDMockito.willAnswer(invocation -> invocation.getArgument(0))
.given(handler).handle(any());
return handler;
That will do the same as your Handler1.handle()
.
Upvotes: 1