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

How to write a junit test for outputStream.write IO IOException

我有以下代码

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 的自定义异常 class。

使用 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 注释。此外,您可以通过在 @Test 注释中声明它来隐藏 try-catch 块。

这样,代码将如下所示:

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