Spring启动集成测试Watch Service Struggles

时间:2017-08-18 18:30:13

标签: java spring-boot watchservice

您在为使用Java监视服务的Spring启动服务编写集成测试时遇到了一些问题。

首先,我要求我的Spring bean在启动时运行,因此实现了ApplicationRunner接口。然后我设置我的监视服务以使用take()方法轮询事件。这将阻止直到收到事件。我遇到的问题是无论我在集成测试中做什么,测试都永远不会执行,因为它似乎阻止了watcher.take()方法

@Component
public class MyClass implements ApplicationRunner {

private static Boolean shutdown;

private WatchService watcher;

@Value("${file.location}")
private String fileLocation;

@Override
public void run(ApplicationArguments args) {

    Path myDir = Paths.get(fileLocation);

    try {
        watcher = myDir.getFileSystem().newWatchService();
        myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        while(true) {
            WatchKey watchKey = watcher.take();
            List<WatchEvent<?>> events = watchKey.pollEvents();
            for (WatchEvent event : events) {
                if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                    //dosomething
                }
            }

            watchKey.reset();
        }
    }

}

我下面的集成测试类似乎永远不会执行我测试的第一行?它只是我的主类的run方法。还有可能在我的集成测试中更改我的fileLocation注入值的值吗?

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestIT {


@Test
public void testFileGetsPickedUpAndProcessed() throws IOException, InterruptedException{

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("pickMe.txt").getFile());

    file.renameTo(new File("/tmp/pickMe.txt"));
    //some assertions

}

1 个答案:

答案 0 :(得分:0)

watcher.take()是一种阻止方法。 确保在另一个线程中运行您的代码以运行测试。

我的申请遇到了同样的问题。这段代码可以正常工作并处理创建/修改事件:

while(true) {
    WatchKey watchKey = watcher.take();
    List<WatchEvent<?>> events = watchKey.pollEvents();
    for (WatchEvent event : events) {

        if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
             handleNewFileCreated(event);
        } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
             handleFileModified(event);
        }
    }

    watchKey.reset();

    // Wait a moment
    Thread.sleep(1000);
}

添加睡眠,切勿让“ while(true)

致谢