如何杀死否定的条件生存变种

uujelgoq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(270)

我有这个代码,我想测试,并获得最大坑覆盖率,但我不能杀死的否定条件,如果(关闭)变种。我还使用mockito抛出一些异常。

public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException {
        try {
            copyBytes(in, out, buffSize);
            if (close) {
                out.close();
                out = null;
                in.close();
                in = null;
            }
        } finally {
            if (close) {
                closeStream(out);
                closeStream(in);
            }
        }
    }

这是我的案例测试:

@Test
        public void mockOutputCopyBytes1False(){
            try{
                OutputStream outputStream = Mockito.mock(OutputStream.class);
                doThrow(new IOException()).when(outputStream).close();
                copyBytes(createInputStream(), outputStream, 50, false);
                outputStream.write(10);
            }catch (Exception e){
                e.printStackTrace();
                Assert.assertEquals(IOException.class, e.getClass());
            }
        }

    @Test
    public void mockOutputCopyBytes1True(){
        try{
            OutputStream outputStream = Mockito.mock(OutputStream.class);
            doThrow(new IOException()).when(outputStream).close();
            copyBytes(createInputStream(), outputStream, 50, true);
            outputStream.write(10);
        }catch (Exception e){
            e.printStackTrace();
            Assert.assertEquals(IOException.class, e.getClass());
        }
    }
at0kjp5o

at0kjp5o1#

这个 finally 无论代码是正常工作还是引发异常,都不需要为这两种情况编写代码:

public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException {
        try {
            copyBytes(in, out, buffSize);
            // TODO - remove the following
            //if (close) {
            //    out.close();
            //    out = null;
            //    in.close();
            //    in = null;
            //}
        } finally {
            if (close) {
                closeStream(out);
                closeStream(in);
            }
        }
    }

相关问题