2

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.

Jason Hu
  • 1,237
  • 2
  • 15
  • 29
  • Put them in a root folder of your project that said the directory just outside `src` or containing. – Smit Dec 05 '13 at 17:06
  • Possible duplicate of http://stackoverflow.com/questions/2597271/easy-to-get-a-test-file-into-junit – Raedwald Dec 05 '13 at 19:27

3 Answers3

6

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 ...

Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35
2

As you keep these test files along with your test code, look at them not as Files, but rather as application resources.

Resources can be located and loaded using a ClassLoader:

// absolute location: if the resource resides at the root
URL url = getClass().getResource("/base_test.txt");

// relative location: if the resource is in the same path as your test classes 
URL url = getClass().getResource("base_test.txt"); 

Assert.assertNotNull(url);

InputStream in= resource.openStream();
// read from resource
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
1

Um, no, unless you are stuck on an old version of JUnit, the answer is you should use the @Rule annotation, as this answer details: Easy way to get a test file into JUnit

Community
  • 1
  • 1
Rob
  • 11,446
  • 7
  • 39
  • 57