Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a method that reads a given file

I know this is a bit naive. How to unit test this piece of code without giving physical file as input. I am new to mockito and unit testing. So I am not sure. Please help.

public static String fileToString(File file) throws IOException
{
    BufferedReader br = new BufferedReader(new FileReader(file));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}
like image 813
user2990315 Avatar asked Dec 20 '13 21:12

user2990315


People also ask

Should unit test read from file?

Strictly speaking, unit tests should not use the file system because it is slow. However, readability is more important. XML in a file is easier to read, and can be loaded in an XML friendly editor.

How can an individual unit test method be executed or debugged?

Select the individual tests that you want to run, open the right-click menu for a selected test and then choose Run Selected Tests (or press Ctrl + R, T). If individual tests have no dependencies that prevent them from being run in any order, turn on parallel test execution in the settings menu of the toolbar.


1 Answers

You can create a file as part of the test, no need to mock it out.

JUnit does have a nice functionality for creating files used for testing and automatically cleaning them up using the TemporaryFolder rule.

public class MyTestClass {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void myTest() {
        // this folder gets cleaned up automatically by JUnit
        File file = folder.newFile("someTestFile.txt");

        // populate the file
        // run your test
    }
}
like image 147
Jeff Storey Avatar answered Sep 18 '22 18:09

Jeff Storey