gpt4 book ai didi

java - 如何为 IOException 编写 junit 测试用例

转载 作者:行者123 更新时间:2023-12-02 10:57:36 25 4
gpt4 key购买 nike

我想检查 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/

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