2

I have problem mock whenNew(File.class) using PowerMockito. Here is my method I want to test:

public void foo() {
    File tmpFile = new File("Folder");
    if (!tmpFile.exists()) {
        if (!configFolder.mkdir()) {
            throw new RuntimeException("Can't create folder");
        }
    }
    File oneFileInFolder = new File(tmpFile, "fileOne.txt");
    if (oneFileInFolder.exists()){
        //do something
    } 
}

Here is test code I wrote:

static File mockFile;
@Before
public void setUp() throws Exception {
    //....some code 
    mockFolder = mock(File.class);
    when(mockFolder.getPath()).thenReturn("Folder");
    when(mockFolder.exists()).thenReturn(true);
    whenNew(File.class).withParameterTypes(String.class).withArguments(anyString()).thenReturn(mockFolder);
    //...some code
}

But when I debug my testcase, I still see a real folder created in my pwd. I don't want folders created when I run my testcases. Any idea?

4

1 回答 1

6

由于您没有在问题中指定这一点,因此可能缺少以下内容:

@PrepareForTest(ClassYoureCreatingTheFileInstanceIn.class)

根据维基

请注意,您必须准备创建 MyClass 新实例以进行测试的类,而不是 MyClass 本身。例如,如果执行 new MyClass() 的类称为 X,那么您必须执行 @PrepareForTest(X.class) 才能使 whenNew 工作。

换句话说,是您的示例X中包含的类。foo()

于 2013-09-11T21:15:21.117 回答