1

简介:考虑以下简化的单元测试:

@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

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

4

2 回答 2

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

    }
}
于 2013-03-26T13:00:10.490 回答
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);
}
于 2013-03-26T12:58:20.487 回答