用Java模拟文件

Fra*_*ank 8 java unit-testing

我正在尝试为采用String文件名的方法编写单元测试,然后打开文件并从中读取.因此,为了测试该方法,我考虑编写一个文件,然后调用我的方法.但是,在构建服务器场中,无法将文件任意写入磁盘.有没有一种标准的方法来"模拟"我的单元测试中有一个真实的文件?

esa*_*saj 17

我发现MockitoPowermock是一个很好的组合.实际上有一个带有示例的博客文章,其中File-class的构造函数被模拟用于测试目的.这也是我拼凑的一个小例子:

public class ClassToTest
{
    public void openFile(String fileName)
    {
        File f = new File(fileName);
        if(!f.exists())
        {
            throw new RuntimeException("File not found!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Mockito + Powermock进行测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToTest.class)
public class FileTest
{
    @Test
    public void testFile() throws Exception
    {
        //Set up a mocked File-object
        File mockedFile = Mockito.mock(File.class);
        Mockito.when(mockedFile.exists()).thenReturn(true);

        //Trap constructor calls to return the mocked File-object
        PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile);

        //Do the test
        ClassToTest classToTest = new ClassToTest();
        classToTest.openFile("testfile.txt");

        //Verify that the File was created and the exists-method of the mock was called
        PowerMockito.verifyNew(File.class).withArguments("testfile.txt");
        Mockito.verify(mockedFile).exists();
    }
}
Run Code Online (Sandbox Code Playgroud)


Woo*_*Moo -2

这是非常令人皱眉的:

最少数量的可测试代码。通常是单个方法/函数,不使用其他方法或类。快速地!数千个单元测试可以在十秒或更短的时间内运行!单元测试从不使用:

  • 一个数据库
  • 应用程序服务器(或任何类型的服务器)
  • 文件/网络 I/O 或文件系统;
  • 另一个应用程序;
  • 控制台(System.out、System.err 等)
  • 记录
  • 大多数其他类(例外包括 DTO、String、Integer、mock 以及其他一些类)。”

来源

如果必须从文件中读取,请预先生成一个测试文件以供所有单元测试读取。无需向磁盘写入任何内容。

  • 我不明白这个答案——问题涉及测试执行文件 I/O 的方法。测试本身明确不执行任何文件 I/O。对于单元测试来说,这是完全可以接受的情况。 (16认同)