0

I got the problem that after mocking the java.io.File(File parent, String childName) constructor with PowerMock still the original constructor is invoked.

Here is the coding:

Class under test:

import java.io.File;

public class ConstructChildFile {
  public File newChildFile(File parent, String childName) {
    return new File(parent, childName);
  }
}

Test case:

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Test;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;

@PrepareForTest({File.class, ConstructChildFile.class})
public class TestConstructorMocking {

  @Test
  public void test() throws Exception {

    File mockedFolder = EasyMock.createMock(File.class);
    File mockedChild = EasyMock.createMock(File.class);
    PowerMock.expectNew(File.class, mockedFolder, "test").andReturn(mockedChild).anyTimes();

    EasyMock.replay(mockedFolder, mockedChild);
    PowerMock.replay(File.class, ConstructChildFile.class);

    System.out.println(new ConstructChildFile().newChildFile(mockedFolder, "test"));
  }
}

So when ConstructChildFile.newChildFile(...) is invoked I expect to get the mockedChild instance since I mocked the constructor a few lines above. Still this does not happen - the actual constructor is called.

The test fails with:

java.lang.NullPointerException
    at java.io.File.<init>(File.java:363)
    at test.ConstructChildFile.newChildFile(ConstructChildFile.java:7)
    at test.TestConstructorMocking.test(TestConstructorMocking.java:24)
...

Any ideas?

vap78
  • 1,029
  • 2
  • 11
  • 26

0 Answers0