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