2016-04-05 142 views
0

JUNITテストでIOExceptionクラスをチェックしたいと思います。ここに私のコードは次のとおりです。IOExceptionのjunitテストケースを書く方法

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テストを取得したい。ご助力ありがとうございます。

+1

このメソッドを呼び出す方法のコードを示してください。 [docによると(https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String))、それは 'パス 'は'ヌル 'です。 –

+0

モッキングツールを使用しますか?さもなければ、それは不必要に複雑になるでしょう。 – dambros

+0

はい、私はMockitoを使用する予定です。 voidメソッドのモックを書くのは混乱しています。あなたが私に模擬することができるシナリオを私に提供できるのであれば、本当に役に立ちます。あなたの助けは本当に感謝しています。 – user6090970

答えて

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

easymockの代わりにeasymockのimport文を 'import static org.mockito.Mockito。* 'で置き換えることで、easymockと同じテストケースを使うことができます。 ; 'testReadProperties内にあります。' InputStream in = mock(InputStream.class); when(in.read())。thenThrow(新しいIOException()); ' – uniknow

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ルール" セクションまでスクロールします。

関連する問題