首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JUnit:检查是否调用了空方法

JUnit:检查是否调用了空方法
EN

Stack Overflow用户
提问于 2010-05-12 05:36:23
回答 3查看 37.5K关注 0票数 12

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

代码:

代码语言:javascript
运行
复制
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");
    }
}

测试:

代码语言:javascript
运行
复制
@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();
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-05-12 05:39:14

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

请参阅this page中的第4点

例如:

代码语言:javascript
运行
复制
verify(mockedObject, times(1)).onChange(); // times(1) is the default and can be omitted
票数 20
EN

Stack Overflow用户

发布于 2010-05-12 05:48:46

下面是您的测试的一个简单修改。

代码语言:javascript
运行
复制
@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();
 }
票数 7
EN

Stack Overflow用户

发布于 2010-05-12 05:48:19

据我所知,您的PropertyFileWatcher应该是子类化的。那么,为什么不像下面这样子类化它:

代码语言:javascript
运行
复制
class TestPropertyFileWatcher extends PropertyFileWatcher
{
     boolean called = false;
     protected void onChange(File file) {
         called = true;
     }
}

...
TestPropertyFileWatcher watcher = new TestPropertyFileWatcher
...
assertTrue(watcher.called);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2814635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档