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?
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();
}
                With Mockito, you can verify whether a method is called at least once/never.
See point 4 in this page
eg:
verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted
                        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();
 }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With