I have a very simple filewatcher 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 ik the onChange method is getting called in a unit test?
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
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();
}