我有一个非常简单的文件监视器类,它每隔2秒检查一次文件是否发生了更改,如果更改了,则调用onChange方法(onChange)。有没有一种简单的方法来检查单元测试中是否调用了onChange方法?
代码:
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
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();
}发布于 2010-05-12 05:39:14
使用Mockito,您可以验证一个方法是否至少被调用一次/从不被调用。
请参阅this page中的第4点
例如:
verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted发布于 2010-05-12 05:48:46
下面是您的测试的一个简单修改。
@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();
}发布于 2010-05-12 05:48:19
据我所知,您的PropertyFileWatcher应该是子类化的。那么,为什么不像下面这样子类化它:
class TestPropertyFileWatcher extends PropertyFileWatcher
{
boolean called = false;
protected void onChange(File file) {
called = true;
}
}
...
TestPropertyFileWatcher watcher = new TestPropertyFileWatcher
...
assertTrue(watcher.called);https://stackoverflow.com/questions/2814635
复制相似问题