测试Spring Integration没有设置IntegrationFlows

时间:2016-01-26 18:24:06

标签: java spring unit-testing spring-boot spring-integration

我在测试使用Spring Integration和Spring Integration DSL的应用程序时遇到了问题。当我运行我的应用程序时,流程设置正确,没有问题但是对于我的测试我想隔离某些流程并对它们进行一些组件测试,所以我需要将流程隔离,即不能指向SpringBootApplication类,否则将拾取应用程序中的其他流。我已尝试使用@SpringApplicationConfiguration@ContextConfiguration注释,但没有成功。

我已经设置了我的测试类(参见下面的代码):

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyService.class, MyServiceTestBeans.class})
@TestPropertySource("classpath:/test_application.properties")
public class MyServiceTest {
    @Autowired
    private RestOperations restOperations;

    @Autowired
    private MyService testObject;

    @Test
    public void testRequestValidObject() throws IOException {
        MyObject expectedMyObject = new MyObject();

        final String id = "valid-id";
        expectedMyObject.setId(id);
        when(restOperations.exchange(any(RequestEntity.class), eq(MyObject.class)))
            .thenReturn(ResponseEntity.ok(expectedMyObject));
        final Message<String> messageToSend = MessageBuilder.withPayload(id)
                .build();
       testObject.inputChannel().send(messageToSend);

        ((DirectChannel) testObject.outputChannel()).subscribe(message -> {
            assertEquals(expectedMyObject, message.getHeaders().get("myObject", MyObject.class));
        });

    }
}

我的MyService类:

@Configuration
public class MyService {
    @Autowired
    private RestOperations restOperations;

    @Value("myServiceWebService")
    private String webServiceName;

    @Bean
    public MessageHandler webServiceMessageHandler() {
         return new WebServiceMessageHandler(webServiceName, restOperations);
    }

    @Bean
    public MessageChannel inputChannel() {
        return MessageChannels.direct("inputChannel").get();
    }

    @Bean
    public MessageChannel outputChannel() {
       return MessageChannels.direct("outputChannel").get();
    }

    @Bean
    public MessageChannel myObjectChannel() {
        return Message.direct("myObject").get();
    }

    @Bean
    public IntegrationFlow getMyObject() {
          return IntegrationFlows.from(inputChannel())
               .handle(webServiceMessageHandler())
               .get();
    }

    @Bean
    public IntegrationFlow returnMyObjectToOutputFlow() {
        return IntegrationFlows.from(myObjectChannel())
             .channel(outputChannel())
             .get();
    }
}

与运行应用程序时不同的是,没有关于Spring连接流的输出,但是控制台上有输出声明它已经拾取了IntegrationFlow bean但是它没有对它们做任何事情。因此,给我一个可怕的调度员没有订阅者&#39;运行测试时出现消息异常(由testObject.inputChannel().send(messageToSend)引起)。

似乎应用程序启动的方式完全不同,并且在运行测试时会跳过设置IntegrationFlow的步骤。

我有什么遗失的吗?有没有办法将测试的配置设置为仅仅是这个组件所需的bean?

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

@SpringBootApplication带来所有需要正确引导您的应用程序。包括IntegrationAutoConfiguration

因此,使用配置的某些部分进行原始测试,您应该手动携带环境。 @EnableIntegrationMyService并列@Configuration