首页 > 解决方案 > 模拟 (file.exists() && file.isDirectory() java

问题描述

我有一个检查文件存在的java方法..

public String checkFileExistance(String arg) throws IOException {

String FolderPath = SomePath

File file = new File(FolderPath);

if (file.exists() && file.isDirectory()) {

//Do something here

}
}

我想模拟 file.exist() 和 file.isDirectory() 让它总是返回true

我尝试了以下方法:

public void test_checkFileExistance1() throws IOException {

/**Mock*/

File mockedFile = Mockito.mock(File.class);
Mockito.when(mockedFile.exists()).thenReturn(true);
Mockito.when(mockedFile.isDirectory()).thenReturn(true);


/**Actual Call*/
ProcessClass.checkFileExistance("arg");
}

但它总是返回false

标签: javamockitojunit4

解决方案


您模拟 a File,但这不是您班级中使用的。在你的类中,你调用new File(...)它返回一个真实的 File Object; 不是你准备的那个。

您可以使用 PowerMockito 来执行此操作。

类似于以下内容:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheClassWithTheCheckFileExistanceMethod.class)
public class TheTest {

    @Before
    public void setup() {
        final File mockFile = mock(File.class);
        Mockito.doReturn(true).when(mockFile).exists();
        // Whatever other mockery you need.

        PowerMockito.whenNew(File.class).withAnyArguments()
                .thenReturn(mockFile);
    }
}

会这样做。


推荐阅读