@SpringBootTest 装饰器导致测试卡在 WatchService 中

@SpringBootTest decorator causes test to get stuck for WatchService

我有一个简单的应用程序,我想用它来监视一个目录,到目前为止我使用的方法是使用 WatchService class:

应用类:

@SpringBootApplication
public class MmsdirectorywatcherApplication {

    public static void main(String[] args) {
        SpringApplication.run(MmsdirectorywatcherApplication.class, args);
    }

    @Autowired
    DirectoryWatcher directoryWatcher;

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            directoryWatcher.startWatching();
        };
    }

}

DirectoryWatcher:

@Component
public class DirectoryWatcher {

    WatchService watchService;
    Path path;
    private String watcherDiretory;

    public DirectoryWatcher() {
    }


    @Value("${mms.directorywatcher.directory}")
    public void setWatcherDiretory(String watcherDiretory) {
        this.watcherDiretory = watcherDiretory;
    }

    public void startWatching(){
        path = Paths.get(watcherDiretory);
        try{
            watchService
                    = FileSystems.getDefault().newWatchService();

            path.register(
                    watchService,
                    StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE,
                    StandardWatchEventKinds.ENTRY_MODIFY);

            WatchKey key;
            while ((key = watchService.take()) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    System.out.println(
                            "Event kind:" + event.kind()
                                    + ". File affected: " + event.context() + ".");
                }
                key.reset();
            }
        }
        catch (IOException ex){

        }
        catch (InterruptedException ex){

        }


    }
}

这 运行 很好,但我想测试应用程序是否正确启动,这里是测试:

@SpringBootTest(classes = {MmsdirectorywatcherApplication.class})
class MmsdirectorywatcherApplicationTests {
    @Autowired
    private DirectoryWatcher directoryWatcher;
    @Test
    void contextLoads() {
        assertNotNull(directoryWatcher);
    }

}

当我 运行 测试时,它似乎卡住了,好像有什么东西阻止它完成。可能是 watchService 本身,但我不确定如何解决这个问题,因为我确实想最终测试是否调用了 startWatching。

谢谢你的时间

您的上下文开始调用 startWatching(),而该函数从未 returns。请注意,watchService.take() 将阻塞,直到有事件发生。