So I'm trying to mock a FileOutputStream but it fails with a NullPointer Exception because I can not mock the method isInvalid from File. First the Code i want to mock:
FileOutputStream fos = null;
fos = createFileOutputStream( file )
...
public FileOutputStream createFileOutputStream( File clsFile ) throws FileNotFoundException
{
return new FileOutputStream( clsFile );
}
My relating mocks:
File clsFile = Mockito.mock( File.class );
Mockito.when( clsUnitUnderTest.createNewFile( strTargetPath + "XXX" + strTargetFileName ) ).thenReturn( clsFile );
Mockito.when( clsFile.exists() ).thenReturn( true );
Mockito.when( clsFile.createNewFile() ).thenReturn( true );
Mockito.when( clsFile.renameTo( new File( strTargetPath + strTargetFileName ) ) ).thenReturn( false );
Mockito.when( clsFile.getPath() ).thenReturn( strTargetPath + "XXX" + strTargetFileName );
// Mockito.when( clsFile.isInvalid ).thenReturn( false ); not working because isInvalid is final!!
FileOutputStream clsFileOutputStream = Mockito.mock( FileOutputStream.class );
Mockito.when( clsUnitUnderTest.createFileOutputStream( clsFile ) ).thenReturn( clsFileOutputStream );
I know there is no way to mock the final method isInvalid. But is there another way to fix this without using PowerMokito?
I also tried using spy instead of mock for the clsFileOutputStream, but this doesn't work because there's no constructor with 0 args.