如何为IOException编写junit测试用例

时间:2016-04-05 14:28:52

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

当我尝试给出false属性文件路径时,它会给出NullPointerException。我想获得IOException和Junit测试。非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

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

警告:动态创建上面的代码而不通过编译进行验证,因此可能存在语法错误。

答案 1 :(得分:0)

试试这个

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”部分。

答案 2 :(得分:0)

检查this答案。简而言之:您可以模拟要引发异常的资源,并在测试中通过模拟来引发异常。 Mockito框架可能会帮助您。详细信息在我之前提供的链接下