2013-03-26 101 views
1

簡介:考慮以下簡化單元測試:測試,在一個匿名類實例的方法被調用

@Test 
public void testClosingStreamFunc() throws Exception { 
    boolean closeCalled = false; 
    InputStream stream = new InputStream() { 
     @Override 
     public int read() throws IOException { 
      return -1; 
     } 

     @Override 
     public void close() throws IOException { 
      closeCalled = true; 
      super.close(); 
     } 
    }; 
    MyClassUnderTest.closingStreamFunc(stream); 
    assertTrue(closeCalled); 
} 

顯然,這是行不通的,抱怨closed不是final

問題:什麼是驗證被測功能無法在這裏調用一些方法,比如close(),在Java單元測試方面最好,最慣用的方式是什麼?

回答

2

怎麼樣使用常規的類實例變量:

class MyInputStream { 
    boolean closeCalled = false; 

    @Override 
    public int read() throws IOException { 
     return -1; 
    } 

    @Override 
    public void close() throws IOException { 
     closeCalled = true; 
     super.close(); 
    } 

    boolean getCloseCalled() { 
     return closeCalled; 
    } 
}; 
MyInputStream stream = new MyInputStream(); 

如果你不想創建自己的類可以考慮使用任何嘲弄的框架,例如與Jmokit:

@Test 
public void shouldCallClose(final InputStream inputStream) throws Exception { 
    new Expectations(){{ 
     inputStream.close(); 
    }}; 

    MyClassUnderTest.closingStreamFunc(inputStream); 
} 
+0

對不起,我不知道發生了什麼,我完全誤讀了代碼。 – ppeterka 2013-03-26 13:04:21

2

我想你應該看看mockito這是做這種測試的框架。

例如,您可以檢查調用次數:http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#4

import java.io.IOException; 
import java.io.InputStream; 

import org.junit.Test; 

import static org.mockito.Mockito.*; 

public class TestInputStream { 

    @Test 
    public void testClosingStreamFunc() throws Exception { 
     InputStream stream = mock(InputStream.class); 
     MyClassUnderTest.closingStreamFunc(stream); 
     verify(stream).close(); 
    } 

    private static class MyClassUnderTest { 
     public static void closingStreamFunc(InputStream stream) throws IOException { 
      stream.close(); 
     } 

    } 
} 
+0

源代碼將使這個答案完成... – ppeterka 2013-03-26 13:02:58

相關問題