JUnit: checking if a void method gets called

Posted by nkr1pt on Stack Overflow See other posts from Stack Overflow or by nkr1pt
Published on 2010-05-11T21:36:22Z Indexed on 2010/05/11 21:44 UTC
Read the original article Hit count: 294

Filed under:
|

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();
 }

© Stack Overflow or respective owner

Related posts about java

Related posts about junit