繁体   English   中英

如何为 IOException 编写 junit 测试用例

[英]How to write junit test cases for 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”部分。

检查这个答案。 简而言之:您可以模拟要抛出异常的资源,并在测试中通过模拟抛出异常。 Mockito 框架可能会帮助你解决这个问题。 详细信息在我之前提供的链接下

不确定我们如何使用当前实现模拟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");
}

并创建一个模拟的 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);
   }
} 

警告:在没有通过编译验证的情况下即时创建上面的代码,因此可能存在语法错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM