-2

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.

so_user
  • 333
  • 3
  • 15
  • 2
    Why would anyone downvote that, are too simple questions qetting downvoted? The question is specific, and I can't see any reason to downvote. – so_user Dec 31 '14 at 10:27
  • 1
    i didn't downvote, but showing no effort is a downvote reason, you should try hard first. – İsmet Alkan Dec 31 '14 at 10:28
  • You can do it like: List files = Lists.newArrayList( mock(File.class), mock(File.class), mock(File.class) ); – Dmitry Dec 31 '14 at 10:55
  • possible duplicate of [Mockito - Mocking behaviour of a File](http://stackoverflow.com/questions/17163484/mockito-mocking-behaviour-of-a-file) – Jonathan Jan 05 '15 at 11:19

3 Answers3

6

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)

NamshubWriter
  • 23,549
  • 2
  • 41
  • 59
0

Yes, you can do it in one line:

List<File> files = Lists.newArrayList( mock(File.class), mock(File.class), mock(File.class) ); 

But I'm not sure it is a good solution. java.io.File is immutable, so it would be pretty useless. I would recommend to use null if you do not have a path to actual file (even if file is not exist it self)

Dmitry
  • 2,069
  • 4
  • 15
  • 23
0

If you just want to create arbitrary files then you can do something like this:

final List<File> files = Stream.generate(() -> mock(File.class)).limit(3).collect(toList());

But obviously you cannot stub any methods on those mocks, etc.. So depending on what you want to do, your original approach may be more useful.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166