【问题标题】:How to write a junit test for outputStream.write IO IOException如何为 outputStream.write IO IOException 编写 junit 测试
【发布时间】:2018-08-16 14:04:14
【问题描述】:

我有以下代码

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 的自定义 Exception 类。

【问题讨论】:

  • 好吧,创建一个扩展 OutputStream 并在调用其 write 方法时抛出 IOException 的类,将该 OutputStream 传递给您的方法,并检查您的方法是否抛出了您期望它抛出的内容。使用模拟框架会使这件事变得更容易一些,但并不多。

标签: java junit ioexception


【解决方案1】:

使用 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
        }
    }

如果您在其他测试方法中也需要该虚拟对象,则应在测试用例中声明一个成员变量,并在带有@Before 注释的setUp 方法中对其进行初始化。此外,您可以通过在 @Test 注释中声明 try-catch-block 来隐藏它。

这样,代码将如下所示:

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

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2022-11-04
    • 1970-01-01
    • 2022-11-03
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多