首页 > 解决方案 > 如何为 spring-batch-integration 编写集成测试?

问题描述

我正在使用与 spring-batch 捆绑在一起的 spring-integration 并且在尝试编写集成测试来测试整个流程时遇到了困难,而不仅仅是单个配置。

我为此测试创建了嵌入式 Sftp 服务器并尝试将消息发送到 sftpInboundChannel - 消息已发送,但没有任何反应,但是当我将此消息发送到下一个通道(在 sftpInboundChannel 之后)时,一切正常。即使我正在使用@TestPropertySource 注释,我也无法加载测试源属性。

这是我的课堂注释


@TestPropertySource(properties = {
  //here goes all the properties
})
@EnableConfigurationProperties
@RunWith(SpringRunner.class)
@Import({TestConfig.class, SessionConfig.class})
@ActiveProfiles("it")
@SpringIntegrationTest
@EnableIntegration
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)

这是我的班级

    @Autowired
    private PollableChannel sftpInboundChannel;

    @Autowired
    private SessionFactory<ChannelSftp.LsEntry> defaultSftpSessionFactory;

    @Autowired
    private EmbeddedSftpServer server;

@Test
    public void shouldDoSmth() {

        RemoteFileTemplate<ChannelSftp.LsEntry> template;
        try {
            template = new RemoteFileTemplate<>(defaultSftpSessionFactory);
            SftpTestUtils.moveToRemoteFolder(template);

            final List<ChannelSftp.LsEntry> movedFiles = SftpTestUtils.listFilesFromDirectory("folder/subfolder", template);
            log.info("Moved file {}", movedFiles.size());

            final MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Sample.txt") // path to file
                .setHeader("file_Path", "Sample.txt")

            boolean wasSent = this.sftpInboundChannel.send(messageBuilder.build());

            log.info("Was sent to sftpInboundChannel channel {}", wasSent);

            log.info("message {}", messageBuilder.build());
        } finally {
            SftpTestUtils.cleanUp();
        }
    }

标签: spring-batchspring-integration-sftp

解决方案


对于不读取属性文件的情况,一种解决方案是在您的 Test 类中添加如下内容:

@BeforeClass
    public static void beforeClass() {
        System.setProperty("propertyfile",  "nameOfFile.properties");
     }

第二种方法是在添加标签的地方创建一个 xml(或类)配置:

<context:property-placeholder
    location="nameOfFile.properties"
    ignore-resource-not-found="true" system-properties-mode="OVERRIDE" />

您的文件将被本地化。

属性文件应该在资源文件夹内。


推荐阅读