Java JUnit:检查是否调用了 void 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2814635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit: checking if a void method gets called
提问by nkr1pt
I have a very simple file watcher class which checks every 2 seconds if a file has changed and if so, the onChange
method (void) is called.
Is there an easy way to check if the onChange
method is getting called in a unit test?
我有一个非常简单的文件观察器类,它每 2 秒检查一次文件是否已更改,如果已更改,则onChange
调用方法 (void)。有没有一种简单的方法来检查该onChange
方法是否在单元测试中被调用?
code:
代码:
public class PropertyFileWatcher extends TimerTask {
private long timeStamp;
private File file;
public PropertyFileWatcher(File file) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if (this.timeStamp != timeStamp) {
this.timeStamp = timeStamp;
onChange(file);
}
}
protected void onChange(File file) {
System.out.println("Property file has changed");
}
}
Test:
测试:
@Test
public void testPropertyFileWatcher() throws Exception {
File file = new File("testfile");
file.createNewFile();
PropertyFileWatcher propertyFileWatcher = new PropertyFileWatcher(file);
Timer timer = new Timer();
timer.schedule(propertyFileWatcher, 2000);
FileWriter fw = new FileWriter(file);
fw.write("blah");
fw.close();
Thread.sleep(8000);
// check if propertyFileWatcher.onChange was called
file.delete();
}
采纳答案by ryanprayogo
回答by doublep
As I understand, your PropertyFileWatcher
is meant to be subclassed. So, why not subclass it like this:
据我了解,您PropertyFileWatcher
的目的是被子类化。那么,为什么不像这样子类化它:
class TestPropertyFileWatcher extends PropertyFileWatcher
{
boolean called = false;
protected void onChange(File file) {
called = true;
}
}
...
TestPropertyFileWatcher watcher = new TestPropertyFileWatcher
...
assertTrue(watcher.called);
回答by Alexander Pogrebnyak
Here is a simple modification for your test.
这是对您的测试的简单修改。
@Test
public void testPropertyFileWatcher() throws Exception {
final File file = new File("testfile");
file.createNewFile();
final AtomicBoolean hasCalled = new AtomicBoolean( );
PropertyFileWatcher propertyFileWatcher =
new PropertyFileWatcher(file)
{
protected void onChange ( final File localFile )
{
hasCalled.set( true );
assertEquals( file, localFile );
}
}
Timer timer = new Timer();
timer.schedule(propertyFileWatcher, 2000);
FileWriter fw = new FileWriter(file);
fw.write("blah");
fw.close();
Thread.sleep(8000);
// check if propertyFileWatcher.onChange was called
assertTrue( hasCalled.get() );
file.delete();
}