0

I am trying to mock the following objects. However, the File object gets mocked, but the PdfReader does not. I am not sure why that is. The moment a new file object is created, it is mocked, while the PdfReader is not.

@Before
public void setup() throws Exception{
    File file = Mockito.mock(File.class);
    PowerMockito.whenNew(java.io.File.class).withAnyArguments().thenReturn(file);

    PdfReader pdfReader = Mockito.mock(PdfReader.class);
    PowerMockito.whenNew(PdfReader.class).withAnyArguments().thenReturn(pdfReader);
}

Code:

protected void method(final String filePath, final String tmpFilePath)
        throws Exception {

    File file = new File(filePath);
    file.renameTo(new File(tmpFilePath));
    final PdfReader reader = new PdfReader(tmpFilePath);
user
  • 854
  • 2
  • 12
  • 28
  • I think you need to reconsider your unit test case and logic. You can not test and mock concrete types while creating "new instance" in your code. You can not inject dependencies and mock them in that way. – Emre Savcı Nov 27 '18 at 05:55
  • You are mocking PdfReader initialization `withAnyArguments` but you're actually calling the constructor with a String argument. `new PdfReader(tmpFilePath);`. Maybe [this other SO Answer](https://stackoverflow.com/a/26323140/947199) coul help – troig Nov 27 '18 at 08:58

0 Answers0