首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@SpringBootTest装饰器导致WatchService测试卡住

@SpringBootTest装饰器导致WatchService测试卡住
EN

Stack Overflow用户
提问于 2020-11-10 04:00:51
回答 1查看 57关注 0票数 0

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

ApplicationClass:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
@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){

        }


    }
}

这运行得很好,但我想测试一下applicationStarted是否正确,下面是测试:

代码语言:javascript
复制
@SpringBootTest(classes = {MmsdirectorywatcherApplication.class})
class MmsdirectorywatcherApplicationTests {
    @Autowired
    private DirectoryWatcher directoryWatcher;
    @Test
    void contextLoads() {
        assertNotNull(directoryWatcher);
    }

}

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

感谢您抽出时间

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-10 04:25:22

您的上下文启动调用startWatching(),而该函数永远不会返回。请注意,watchService.take()将阻塞,直到事件传入。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64758476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档