Search code examples
junitstatic-methodsfileoutputstreampowermockito

how to mock "new FileOutputStram()" written in public static method using Powermockito


Problem: I am writing a test case for a method from which a public static method with below code is called:

final File file = new File(filePath);
    final OutputStream out = new FileOutputStream(file);
    out.write(bytes);
    out.close();

Now I need to mock the above calls.

What I have written:-

@Before
public void setUp() throws Exception{
  File myFile = PowerMockito.mock(File.class);
  FileOutputStream outStream = PowerMockito.mock(FileOutputStream.class);

  PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(myFile);        
  PowerMockito.whenNew(FileOutputStream.class).withAnyArguments().thenReturn(outStream);

  doNothing().when(outStream).write(Matchers.any());
  doNothing().when(outStream).close();
}

@Test
public void testMethod(){
  PowerMockito.mockStatic(StaticClassUtil.class);
  PowerMockito.when(StaticClassUtil.uploadFile(file.getBytes(), "dummy","dummy","dummy", null)).thenReturn("dummy");        
}

While debugging I found No mock object at line :

    final File file = new File(filePath);

Please suggest where I am getting wrong.


Solution

  • Most likely you missed one of the steps outlined in the documentation - probably you forgot to use @PrepareForTest for File.class and FileOutputStream.class.

    But the real answer: you don't necessarily have to call new directly in your code. You can turn to dependency injection frameworks to do that for you, or simply have an OutputStream passed into your method under test. Because then you only pass a mocked object, and your need to mock those pesky calls to new() vanish in thin air. And you can stick with good old Mockito instead of PowerMock(ito).