我想检查 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");
}
当我尝试提供错误的属性文件路径时,它给出 NullPointerException。我想要对其进行 IOException 和 Junit 测试。非常感谢您的帮助。
最佳答案
试试这个
public TestSomeClass
{
private SomeClass classToTest; // The type is the type that you are unit testing.
@Rule
public ExpectedException expectedException = ExpectedException.none();
// This sets the rule to expect no exception by default. change it in
// test methods where you expect an exception (see the @Test below).
@Test
public void testxyz()
{
expectedException.expect(IOException.class);
classToTest.loadProperties("blammy");
}
@Before
public void preTestSetup()
{
classToTest = new SomeClass(); // initialize the classToTest
// variable before each test.
}
}
一些阅读: jUnit 4 Rule - 向下滚动到“ExpectedException Rules”部分。
关于java - 如何为 IOException 编写 junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36429274/