Like a unit test method that reads a given file

I know this is a bit naive. Like a unit test, this piece of code without specifying a physical file. I am new to mockito and unit testing. Therefore, 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(); } } 
+8
java file unit-testing junit mockito
source share
3 answers

You should probably reorganize your method. As you understand, a method that takes a file as input is not easy to verify. Furthermore, it seems static, which does not help testing. If you rewrite your method as:

 public String fileToString(BufferedReader input) throws IOException 

it will be much easier to test. You separate your business logic from the technical characteristics of reading a file. As far as I understand, your business logic reads the stream and ensures that line endings are unix style.

If you do, your method will be checked. You also make it more general: now it can read from a file, from a URL, or from any stream. Better code, easier to check ...

+6
source share

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

JUnit has good functionality for creating files used for testing and automatically cleaning them 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 } } 
+13
source share

Why do you want to make fun of a file? Mocking java.io.File is a bad idea as it has many downloads. I would advise you to make sure that the minimum text file is available in the classpath when performing unit tests. You can convert this file to text and confirm the output.

+3
source share

All Articles