nkr1pt
nkr1pt

Reputation: 4666

JUnit: checking if a void method gets called

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

Upvotes: 12

Views: 38552

Answers (3)

ryanprayogo
ryanprayogo

Reputation: 11817

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

Upvotes: 21

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

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

Upvotes: 7

user319799
user319799

Reputation:

As I understand, your PropertyFileWatcher is meant to be subclassed. So, why not subclass it like this:

class TestPropertyFileWatcher extends PropertyFileWatcher
{
     boolean called = false;
     protected void onChange(File file) {
         called = true;
     }
}

...
TestPropertyFileWatcher watcher = new TestPropertyFileWatcher
...
assertTrue(watcher.called);

Upvotes: 4

Related Questions