【问题标题】:Mocking (file.exists() && file.isDirectory() java模拟 (file.exists() && file.isDirectory() java
【发布时间】:2020-03-05 12:07:51
【问题描述】:

我有一个 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

【问题讨论】:

  • 您没有在模拟对象上调用 exists()isDirectory()。相反,您创建了一个 new File(..) 对象。
  • 我不清楚你能详细说明吗?

标签: java mockito junit4


【解决方案1】:

你模拟了一个File,但这不是你课堂上使用的那个。在您的班级中,您调用 new File(...) 会返回一个 real 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);
    }
}

会这样做。

【讨论】:

    【解决方案2】:

    您在测试方法中创建了一个模拟对象mockedFile。但是这个模拟对象没有在你的 checkExistance() 方法中使用。这是因为您创建了另一个 File 对象并在这个新创建的(并且不是模拟对象)上调用 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);
    }
    

    【讨论】:

    • 遗憾的是我是一名测试人员,无法更改开发人员创建的 checkFileExistance 方法。我只被允许在我的组织中编写 Junit 测试用例。还有其他替代解决方案吗?
    • 您可以尝试模拟ProcessClass.checkFileExistance(String)方法,使其在被调用时返回true
    • 实际方法更大,为了更好地理解,我对其进行了修剪。实际上, checkFileExistance 正在从其他类的其他方法获取文件夹路径并检查文件是否存在。一旦发现file.exists为true,它将用于进一步操作,它不是简单的true false返回方法。
    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    相关资源
    最近更新 更多