代码之家  ›  专栏  ›  技术社区  ›  Salem Masoud

如何为outputStream编写junit测试。write IO IOException

  •  0
  • Salem Masoud  · 技术社区  · 6 年前

    我有以下代码

    public static void writeToOutputStream(byte[] bytesArr, OutputStream outputStream) {
        try {
             outputStream.write(bytesArr);
            }
        catch (IOException e) {
               throw new NetModelStreamingException(
                    "IOException occurd during writing to stream. Error 
                     Message:" + e.getMessage());
            }
    }
    

    我想写一个JUnit来测试我的代码是否会捕获IOException。

    PS:NetModelStreamingException是一个扩展RuntimeException的自定义异常类。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Würgspaß    6 年前

    使用JUnit4+测试异常处理是否如预期的那样的方法可能是这样的(注意,如果没有抛出异常,则需要使测试失败)。

        @Test
        public void testWriteToOutputStreamExceptionHandling() {
            //Dummy object for testing
            OutputStream exceptionThrowingOutputStream = new OutputStream() {
                public void write(byte[] b) throws IOException {
                    throw new IOException(); //always throw exception
                }
                public void write(int b) {} //need to overwrite abstract method
            };
    
            try {
                YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
                fail("NetModelStreamingException expected");
            }
            catch (NetModelStreamingException e) {
                //ok
            }
        }
    

    如果在其他测试方法中也需要该虚拟对象,则应在测试用例中声明成员变量,并在 setUp -方法的注释为 @Before . 而且,你可以隐藏 try-catch -通过在 @Test 注解。

    这样,代码将如下所示:

    private OutputStream exceptionThrowingOutputStream;
    
    @Before
    public void setUp() throws Exception {
        exceptionThrowingOutputStream = new OutputStream() {
            @Override
            public void write(byte[] b) throws IOException {
                throw new IOException();
            }
            @Override
            public void write(int b) {}
        };
    }
    
    @Test(expected = NetModelStreamingException.class)
    public void testWriteToOutputStreamExceptionHandling() throws NetModelStreamingException {
        YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
    }