Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
测试java线程代码_Java_Multithreading_Junit - Fatal编程技术网

测试java线程代码

测试java线程代码,java,multithreading,junit,Java,Multithreading,Junit,我正在测试一个使用WatchService的类。此类有一个方法processEvents,其工作原理如下(从): 编辑:澄清一下,getEvents不应该为空(因为已经创建了一个文件),而且它甚至会被watchservice检测到(打印完成)。但是由于它在不同的线程中运行,测试报告它为空,因此它失败,因为在assertFalse中isEmpty不应为true File tempFile = File.createTempFile("temporary file", null, Paths

我正在测试一个使用WatchService的类。此类有一个方法processEvents,其工作原理如下(从):

编辑:澄清一下,getEvents不应该为空(因为已经创建了一个文件),而且它甚至会被watchservice检测到(打印完成)。但是由于它在不同的线程中运行,测试报告它为空,因此它失败,因为在assertFalse中isEmpty不应为true

    File tempFile = File.createTempFile("temporary file", null, Paths.get(testdirectory).toFile());
    tempFile.deleteOnExit();
    Thread.sleep(5000);
    assertFalse(MyClass.getEvents().isEmpty());
我想5秒钟应该够长了吧


另外,您可能需要使
getEvents
同步或其他什么。

最简单的解决方案是只测试
AddToEvents(event)
代码

创建模拟事件,然后调用您的
AddToEvents(event)
并进行测试,以确保您做了正确的事情


这还有一个额外的好处,就是能够模拟在真实的word环境中很难模拟的事件。

那么,您得到的问题、异常或输出是什么?我的借口、澄清已经添加。我不认为这样做。我已经使getEvents完全按照您给我的方式进行了同步和实现,但是测试失败。您需要查看更多代码,以确定同步是否正确。
@Test
public void testEventAdded() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            synchronized(currentThread) {
                MyClass.processEvents();
            }
        }
    };
    thread.start();
    File tempFile = File.createTempFile("temporary file", null, Paths.get(testdirectory).toFile());
    tempFile.deleteOnExit();
    assertFalse(MyClass.getEvents().isEmpty());
}
    File tempFile = File.createTempFile("temporary file", null, Paths.get(testdirectory).toFile());
    tempFile.deleteOnExit();
    Thread.sleep(5000);
    assertFalse(MyClass.getEvents().isEmpty());