Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用PowerMock的模拟构造函数文件(文件父级,字符串childName)_Java_Unit Testing_Powermock_Easymock - Fatal编程技术网

Java 使用PowerMock的模拟构造函数文件(文件父级,字符串childName)

Java 使用PowerMock的模拟构造函数文件(文件父级,字符串childName),java,unit-testing,powermock,easymock,Java,Unit Testing,Powermock,Easymock,我遇到的问题是,在使用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)

我遇到的问题是,在使用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)
...
java.lang.NullPointerException
位于java.io.File。(File.java:363)
位于test.ConstructChildFile.newChildFile(ConstructChildFile.java:7)
test.TestConstructorMocking.test(TestConstructorMocking.java:24)
...

有什么想法吗?

参考答案的可能副本建议在PrepareForTest注释中包含测试中的类。我已经这样做了。您是否尝试添加
@RunWith(PowerMockRunner.class)
注释?agrr。。。绝对正确-这就成功了!谢谢!如果你愿意,可以加上这个作为答案。没关系!答案已经发布了。