@SpringBootTest decorator导致WatchService的测试陷入停滞



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

应用类别:

@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(),而该函数永远不会返回。请注意,watchService.take()将阻塞,直到出现事件。

相关内容

  • 没有找到相关文章

最新更新