Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - Mocking behaviour of a File

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
    }

}

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.

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.

like image 214
Ren Avatar asked Jun 18 '13 07:06

Ren


1 Answers

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.

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.

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.

like image 75
Jonathan Avatar answered Sep 24 '22 13:09

Jonathan