Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate File in Java

I'm trying to write unit tests for a method that takes a String filename, then opens the file and reads from it. So, to test that method, I thought about writing a file, then calling my method. However, in the build farm, it is not possible to write files arbitrarily to disk. Is there a standard way to "simulate" having a real file in my unit test?

like image 230
Frank Avatar asked Aug 07 '12 15:08

Frank


People also ask

How do I read a JUnit file?

Read File and Resource in JUnit Test Examples Any file under src/test/resources is often copied to target/test-classes. To access these resource files in JUnit we can use the class's resource. It will locate the file in the test's classpath /target/test-classes.


2 Answers

I've found that Mockito and Powermock are a good combination for this. Actually there's a blog post with a sample, where the File-class's constructor is mocked for testing purposes. Here's also a small example I threw together:

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

Testing with 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();
    }
}
like image 123
esaj Avatar answered Sep 23 '22 20:09

esaj


If you use JUnit, there is the TemporaryFolder. Files are deleted after the test. Example given on the page:

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

  @Test
  public void testUsingTempFolder() throws IOException {
      File createdFile= folder.newFile("myfile.txt");
      File createdFolder= folder.newFolder("subfolder");
      // ...
     }
 }

However, I have also used it for testing my Android class read/write capabilities like:

    [...]
    pw = new PrintWriter(folder.getAbsolutePath() + '/' + filename);
    pw.println(data);
like image 28
comodoro Avatar answered Sep 23 '22 20:09

comodoro