我想为 JUnit 测试模拟一个 File 和 FileInputStream 对象。
假设我们有一个解析器。只能通过 parse(File myFile) 方法从 Parser 外部访问。其他方法如 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;
}
}
我面临的问题:
- 如何断言一个文件对象像这个文件一样的文件输入流(PowerMockito)属于这个文件输入流,内容如下
- 如何模拟私有方法(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
}