I would like to mock a File and FileInputStream Object for an JUnit test.
Let us say we are having a Parser. From outside the Parser is just accessible via the parse(File myFile) method. The other methods like readMyStream....are private.
Example Code:
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;
}
}
The problems I face:
- how to assert a File Object an FileInputStream (PowerMockito) like this File belongs to this FileInputStream with the following content
- how to mock a private method (Mockito/PowerMockito)
an example of the Mocking/not working :)....
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
}