How to use existing text files for JUnit tests
file, java, junit
Solution
You can put the file in the root of the classpath (`/bin`, e.g.) and then you can access it as stream using
getClass().getClassLoader().getResourceAsStream("/test.txt")
This would even work, if your classes are packaged as a jar file.
If you need access to the file, you could use
File file = new File(getClass().getClassLoader().getResource("/test.txt").toURI());
Naturally, if you want to put your text file next to your test class or in some other folder, you can use
File file = new File(getClass().getClassLoader().getResource("/net/winklerweb/somepackage/test.txt").toURI());
or any other path ...
Problem
I want to unit test a class that manipulates contents of text files. I have a set of existing text files to serve as test cases. How and where do I store these text files that would be used by the JUnit tests? I've tried putting them in the same directory with the unit test .Java file and tried to access them, but I get a file not found: ``` File baseFile = new File("base_test.txt"); assertTrue(baseFile.exists()); ``` EDIT: as per the answers, I've tried getting the files using `ClassLoader`. The files are there, however when I tried to use the `InputStream` for those files, I am getting a `"Stream Closed"` Exception. I've tried getting the `InputStream` both from the file and the URL: ``` FileInputStream in = new FileInputStream(new File(filename)); ... InputStream in = baseUrl.openStream(); ``` Same exception.