简介:考虑以下简化的单元测试:
@Test
public void testClosingStreamFunc() throws Exception {
boolean closeCalled = false;
InputStream stream = new InputStream() {
@Override
public int read() throws IOException {
return -1;
}
@Override
public void close() throws IOException {
closeCalled = true;
super.close();
}
};
MyClassUnderTest.closingStreamFunc(stream);
assertTrue(closeCalled);
}
显然它不起作用,提示 closed
不是 final
。
问题:在 Java 单元的上下文中,什么是最好或最惯用的方法来验证被测函数确实调用了一些方法,比如这里的 close()
测试?
最佳答案
如何使用带有实例变量的常规类:
class MyInputStream {
boolean closeCalled = false;
@Override
public int read() throws IOException {
return -1;
}
@Override
public void close() throws IOException {
closeCalled = true;
super.close();
}
boolean getCloseCalled() {
return closeCalled;
}
};
MyInputStream stream = new MyInputStream();
如果您不想创建自己的类,请考虑使用任何模拟框架,例如使用 Jmokit:
@Test
public void shouldCallClose(final InputStream inputStream) throws Exception {
new Expectations(){{
inputStream.close();
}};
MyClassUnderTest.closingStreamFunc(inputStream);
}
关于java - 测试匿名类实例中的方法是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637444/