use*_*970 6 java junit ioexception
我想在 JUNIT 测试中检查 IOException 类。这是我的代码:
public void loadProperties(String path) throws IOException {
InputStream in = this.getClass().getResourceAsStream(path);
Properties properties = new Properties();
properties.load(in);
this.foo = properties.getProperty("foo");
this.foo1 = properties.getProperty("foo1");
}
Run Code Online (Sandbox Code Playgroud)
当我尝试给出错误的属性文件路径时,它给出了 NullPointerException。我想对其进行 IOException 和 Junit 测试。非常感谢您的帮助。
uni*_*now -1
不确定我们如何IOException使用当前的实现来模拟,但是如果您以如下方式重构代码:
public void loadProperties(String path) throws IOException {
InputStream in = this.getClass().getResourceAsStream(path);
loadProperties(in);
}
public void loadProperties(InputStream in) throws IOException {
Properties properties = new Properties();
properties.load(in);
this.foo = properties.getProperty("foo");
this.foo1 = properties.getProperty("foo1");
}
Run Code Online (Sandbox Code Playgroud)
并创建一个模拟的 InputStream,如下所示:
package org.uniknow.test;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
public class TestLoadProperties {
@test(expected="IOException.class")
public void testReadProperties() throws IOException {
InputStream in = createMock(InputStream.class);
expect(in.read()).andThrow(IOException.class);
replay(in);
// Instantiate instance in which properties are loaded
x.loadProperties(in);
}
}
Run Code Online (Sandbox Code Playgroud)
警告:上面的代码是即时创建的,没有通过编译进行验证,因此可能存在语法错误。