Mockito - 文件的模拟行为

2022-01-14 00:00:00 unit-testing mockito java

我有一个类,它接收一个文件,找到与之相关的文件,然后打开它.类似于

I have a class that takes in a single file, finds the file related to it, and opens it. Something along the lines of

class DummyFileClass
{
    private File fileOne;
    private File fileTwo;
    public DummyFileClass(File fileOne)
    {
         this.fileOne = fileOne;
         fileTwo = findRelatedFile(fileOne)
    }

    public void someMethod()
    {
         // Do something with files one and two
    }

}

在我的单元测试中,我希望能够测试 someMethod() 而不必将物理文件放在某个地方.我可以模拟 fileOne,并将其传递给构造函数,但由于在构造函数中计算 fileTwo,我无法控制它.

In my unit test, I want to be able to to test someMethod() without having to have physical files sitting somewhere. I can mock fileOne, and pass it to the constructor, but since fileTwo is being calculated in the constructor, I don't have control of this.

我可以模拟 findRelatedFile() 方法 - 但这是最​​佳实践吗?在这里寻找最佳设计而不是实用的解决方法.我对模拟框架还很陌生.

I could mock the method findRelatedFile() - but is this the best practice? Looking for the best design rather than a pragmatic workaround here. I'm fairly new to mocking frameworks.

推荐答案

在这种情况下,我会使用物理文件来测试组件,而不是依赖模拟框架.正如 fge 所提到的,它可能更容易,而且您不必担心您可能对模拟做出任何错误假设.

In this sort of situation, I would use physical files for testing the component and not rely on a mocking framework. As fge mentions it may be easier plus you don't have to worry about any incorrect assumptions you may make of your mock.

例如,如果您依赖 File#listFiles() 你可以让你的模拟返回一个固定的 File 列表,但是,不能保证它们返回的顺序 - 你可以仅在您在不同平台上运行代码时才发现.

For instance, if you rely upon File#listFiles() you may have your mock return a fixed list of Files, however, the order they are returned in is not guaranteed - a fact you may only discover when you run your code on a different platform.

我会考虑使用 JUnit 的 TemporaryFolder 规则帮助您设置测试所需的文件和目录结构,例如:

I would consider using JUnit's TemporaryFolder rule to help you set up the file and directory structure you need for your test, e.g.:

public class DummyFileClassTest {
    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void someMethod() {
        // given
        final File file1 = folder.newFile("myfile1.txt");
        final File file2 = folder.newFile("myfile2.txt");

        ... etc...
    }
}

该规则应在测试完成时清理所有创建的文件和目录.

The rule should clean up any created files and directories when the test completes.

相关文章