Search code examples
javalistjunitmockitodummy-data

How to create a list of dummy files in Java?


I need to create a List<File> files, so that it contains 3 dummy files. How do I do that?

I need that for unit test.

I did

private File file1 = mock(File.class);
private File file2 = mock(File.class);
private File file3 = mock(File.class);

List<File> files = Lists.newArrayList(file1, file2, file3);

But I thought is is all possible in one line.


Solution

  • I would recommend not mocking File and instead make fake values. Methods that act on File instances tend to care about the file path and/or whether the file exists, so the most straight-forward way to do that is to use real instances.

    Here is an example using JUnit4 that creates a list of three File instances to refer to files that don't exist in a directory that does:

    @RunWith(JUnit4.class)
    public class ExampleTest {
      @Rule
      public TemporaryFolder testFolder = new TemporaryFolder();
    
      private final Foo foo = new Foo();
    
      @Test
      public void shouldFailIfFilesDoNotExist() {
        List<File> files = Lists.newArrayList(
            testFolder.newFile(),
            testFolder.newFile(),
            testFolder.newFile());
        foo.doIt(files);
      }
    }
    

    If you care about the filenames, you can pass the name of the file to TemporaryFolder.newFile(String)