使用带有Mockito / PowerMockito的File和FileInputStream测试类

时间:2012-10-17 15:26:05

标签: java junit mockito powermock

我想为JUnit测试模拟一个File和FileInputStream对象。

让我们说我们有一个解析器。从Parser外部可以通过解析(File myFile)方法访问。其他方法如readMyStream ....是私有的。

示例代码:

public class Parser {

   public HashMap<String, String> parse(File myFile) throws Exception {
         HashMap<String, String> myConfig;
         Config config;

         try {
             //this line gives me a headache
             FileInputStream myFileInputStream = new FileInputStream(myFile);

             configStream = readMyStream(myFileInputStream);
               ..........
         } catch (FileNotFoundException e) {
                throw e;
         }
         return myConfig;
   }
   //reads the stream 
   private Config readMyStream(FileInputStream myFileInputStream) {
      Config config;    

      ...JDOM stuff....    

      return config;
   }
}

我遇到的问题:

  • 如何断言File对象FileInputStream(PowerMockito)就像这个File属于这个FileInputStream,内容如下:
  • 如何模拟私有方法(Mockito / PowerMockito)

模拟/不工作的一个例子:)....

public class ParserTest {

   @Test
   public final void testParse() {
      File MOCKEDFILE = PowerMockito.mock(File.class);
      PowerMockito.when(MOCKEDFILE.exists()).thenReturn(true);
      PowerMockito.when(MOCKEDFILE.isFile()).thenReturn(true);
      PowerMockito.when(MOCKEDFILE.isDirectory()).thenReturn(false);
      PowerMockito.when(MOCKEDFILE.createNewFile()).thenReturn(true);
      PowerMockito.when(MOCKEDFILE.length()).thenReturn(11111111L);

      //what about the path of MOCKEDFILE which isn't existing
      PowerMockito.when(MOCKEDFILE.getPath()).thenReturn(?????);

      //how to assign a File an FileInputStream? (I thought something like)
      PowerMockito.mockStatic(FileInputStream.class);
      FileInputStream MOCKEDINPUTSTREAM = PowerMockito.mock(FileInputStream.class);
      PowerMockito.whenNew(FileInputStream.class).withArguments(File.class).thenReturn(MOCKEDINPUTSTREAM);

      //how to mock the private method readMyStream
   }

1 个答案:

答案 0 :(得分:4)

我建议使用File规则并根据需要创建/不创建文件,而不是模仿TemporaryFolder

在我之前的项目中,我们编写了一个FileInputStreamSupplier类,用于创建FileInputStream。然后可以模拟此类以提供模拟的FileInputStream以允许测试行为。一般来说,你可以让你的班级使用Supplier<FileInputStream>(使用番石榴)并嘲笑它。