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();
}
}
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With