模拟(file.exists()和&;file.isDirectory()java

模拟(file.exists()和&;file.isDirectory()java,java,mockito,junit4,Java,Mockito,Junit4,我有一个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()和fil

我有一个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");
}

但是当您在测试方法中创建一个模拟对象
mockedFile
时,它总是返回false

。但是这个模拟对象没有在您的
checkExistance()
方法中使用。这是因为您创建了另一个文件对象并调用
exists()
isDirectory()
这个新创建的对象(而不是模拟对象)上的方法

如果
checkExistance()
方法将文件对象作为参数而不是文件名,则可以将模拟对象传递给该方法,该方法将按预期工作:

public String checkFileExistance(File file) throws IOException {
    if (file.exists() && file.isDirectory()) {
        // do something here
    }
}

public void test_checkFileExistance1() throws IOException {
    File mockedFile = Mockito.mock(File.class);
    Mockito.when(mockedFile.exists()).thenReturn(true);
    Mockito.when(mockedFile.isDirectory()).thenReturn(true);

    /**Actual Call*/
    ProcessClass.checkFileExistance(mockedFile);
}

您模拟了一个
文件
,但它不是您的类中使用的文件。在您的类中,您调用
新文件(…)
,它返回一个真实的
文件
对象,而不是您准备的对象

您可以使用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);
    }
}

将执行此操作。

您不是在模拟对象上调用
exists()
isDirectory()
。而是创建一个
新文件(…)
对象。我不清楚您能否详细说明?遗憾的是,我是一名测试人员,无法更改开发人员创建的checkFileExistance方法。我只允许在我的组织中编写Junit测试用例。是否有其他替代解决方案?您可以尝试模拟
ProcessClass.checkFileExistance(字符串)
method在调用时返回
true
。实际的方法更大,为了更好地理解,我修剪了它。实际上,checkFileExistance是从其他类的其他方法获取folderpath,并检查文件是否存在。一旦找到file.exists为true,它将用于进一步的操作,这不是一个简单的过程真假返回法。