我遇到的问题是,在使用PowerMock模拟java.io.File(File parent,String childName)构造函数之后,仍会调用原始构造函数。
以下是编码:
待测班级:
import java.io.File;
public class ConstructChildFile {
public File newChildFile(File parent, String childName) {
return new File(parent, childName);
}
}
测试用例:
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"));
}
}
因此,当调用ConstructChildFile.newChildFile(...)时,我希望得到mockedChild实例,因为我在上面几行模拟了构造函数。仍然没有发生这种情况 - 实际的构造函数被调用。
测试失败了:
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)
...
有什么想法吗?