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

标签 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");
}

当我尝试提供错误的属性文件路径时,它给出 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/

相关文章:

java - 将 main/java 类添加到我在 intellij 中的 test/java 目录

unit-testing - 对依赖 EJB 和 UserTransaction 的类进行单元测试

java - 更改aws java项目中的配置文件

java - 在 WebSphere 6 上使用可变文件名在 JSP 中包含静态文件

java - Java中的字符串ID是什么意思?

android - 禁用 wifi 时 ConnectException 与 IOException?

java - java.util.zip.ZipFile.close() 什么时候抛出 IOException?

java - 编译问题: Unreachable statement

java - 如何使 IntelliJ/Android Studio 中的静态导入更快

java - 使用 Spring Data Hadoop 类路径资源的 IOException