繁体   English   中英

具有Closeable参数的方法的单元测试

[英]Unit test for method with Closeable parameter

我是单元测试的新手。

如何为该方法编写JUnit测试?

public static void close(Closeable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

尝试:

@Test
public void nominalClose() {
    Closeable closeable = new MyCloseable();
    Assert.assertFalse(closeable.isClosed());
    MyClass.close(closeable);    // call to the method you want to test
    Assert.assertTrue(closeable.isClosed());
}

@Test(expected = RuntimeException.class) 
public void ioExceptionClose() {
    Closeable closeable = new Closeable(){
        @Override
        public void close() {
            throw new IOException("test IO");
        }
    };
    MyClass.close(closeable);    // call should send a RuntimeException
}

// TODO: add more tests? Null? not IOException?

private static class MyCloseable implements Closeable {
    private boolean closed = false;
    @Overrive
    public void close() {
        closed = true;
    }
    public boolean isClosed() {
        return closed;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM