测试是否调用匿名类实例中的方法

时间:2013-03-26 12:47:17

标签: java unit-testing mocking anonymous-class

简介:请考虑使用简化的单元测试:

@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())的最佳或最惯用的方法是什么?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

我认为你应该看看mockito这是一个进行这种测试的框架。

例如,您可以检查调用次数:http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#4

import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import static org.mockito.Mockito.*;

public class TestInputStream {

    @Test
    public void testClosingStreamFunc() throws Exception {
        InputStream stream = mock(InputStream.class);
        MyClassUnderTest.closingStreamFunc(stream);
        verify(stream).close();
    }

    private static class MyClassUnderTest {
        public static void closingStreamFunc(InputStream stream) throws IOException {
            stream.close();
        }

    }
}