gpt4 book ai didi

java - 带有 Closeable 参数的方法的单元测试

转载 作者:行者123 更新时间:2023-11-30 06:18:36 24 4
gpt4 key购买 nike

我是单元测试的新手。

我应该如何为这个方法编写 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;
}
}

关于java - 带有 Closeable 参数的方法的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com