我有一个非常简单的文件监视器类,如果文件已更改,则每2秒检查一次,如果是,onChange则调用方法(void).有没有一种简单的方法来检查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");
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
@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();
}
Run Code Online (Sandbox Code Playgroud)
rya*_*ogo 19
使用Mockito,您可以验证方法是否至少被调用一次/从不.
请参阅本页的第 4点
例如:
verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted
Run Code Online (Sandbox Code Playgroud)
这是对您的测试的简单修改.
@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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36004 次 |
| 最近记录: |