JUnit:检查是否调用了void方法

时间:2010-05-11 21:36:23

标签: java junit

我有一个非常简单的文件监视器类,如果文件已更改,则每2秒检查一次,如果是,则调用onChange方法(void)。 有没有一种简单的方法可以检查单元测试中是否调用onChange方法?

代码:

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

3 个答案:

答案 0 :(得分:18)

使用Mockito,您可以验证方法是否至少被调用一次/从不。

this page

中的第4点

例如:

verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted

答案 1 :(得分:7)

以下是对测试的简单修改。

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

答案 2 :(得分:4)

据我了解,您的PropertyFileWatcher应该是子类。那么,为什么不像这样继承它:

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

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