如何为IOException编写junit测试用例

问题描述 投票:2回答:3

我想在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测试。非常感谢您的帮助。

java junit ioexception
3个回答
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);
   }
} 

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


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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.