【问题标题】:Test that a method in an anonymous class instance gets called测试匿名类实例中的方法是否被调用
【发布时间】:2013-03-16 06:29:32
【问题描述】:

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

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

【问题讨论】:

    标签: java unit-testing mocking anonymous-class


    【解决方案1】:

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

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

    【讨论】:

    • 对不起,我不知道发生了什么,我完全看错了代码。
    【解决方案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();
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多