Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: checking if a void method gets called

Tags:

java

junit

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();
}
like image 617
nkr1pt Avatar asked May 11 '10 21:05

nkr1pt


2 Answers

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
like image 121
ryanprayogo Avatar answered Oct 05 '22 03:10

ryanprayogo


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();
 }
like image 40
Alexander Pogrebnyak Avatar answered Oct 05 '22 01:10

Alexander Pogrebnyak