Java 测试匿名类实例中的方法是否被调用 引言:考虑以下简化单元测试: @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); }

Java 测试匿名类实例中的方法是否被调用 引言:考虑以下简化单元测试: @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); },java,unit-testing,mocking,anonymous-class,Java,Unit Testing,Mocking,Anonymous Class,很明显,这是行不通的,人们抱怨说关闭并不是最终结果 问:在Java单元测试的上下文中,验证被测函数是否调用某些方法(如close here)的最佳或最惯用方法是什么?使用带有实例变量的常规类如何: class MyInputStream { boolean closeCalled = false; @Override public int read() throws IOException { return -1; } @Overrid

很明显,这是行不通的,人们抱怨说关闭并不是最终结果


问:在Java单元测试的上下文中,验证被测函数是否调用某些方法(如close here)的最佳或最惯用方法是什么?

使用带有实例变量的常规类如何:

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

如果您不想创建自己的类,请考虑使用任何嘲弄框架,例如使用JMOKITK:

@Test
public void shouldCallClose(final InputStream inputStream) throws Exception {
    new Expectations(){{
        inputStream.close();
    }};

    MyClassUnderTest.closingStreamFunc(inputStream);
}

使用带有实例变量的常规类如何:

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

如果您不想创建自己的类,请考虑使用任何嘲弄框架,例如使用JMOKITK:

@Test
public void shouldCallClose(final InputStream inputStream) throws Exception {
    new Expectations(){{
        inputStream.close();
    }};

    MyClassUnderTest.closingStreamFunc(inputStream);
}

我认为你应该看看哪一个是做这种测试的框架

例如,您可以检查调用次数:


我认为你应该看看哪一个是做这种测试的框架

例如,您可以检查调用次数:


对不起,我不知道发生了什么,我完全误读了代码。对不起,我不知道发生了什么,我完全误读了代码。