Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a resource file in JUnit test

Tags:

java

junit

I read text file in my unit test and I placed some input text files in resources folder. Following is the directory structure.

  • src -> com -> au -> myapp -> util -> MyFileReader
  • test -> com -> au -> myapp -> util -> MyFileReaderTest
  • test -> com -> au -> myapp -> resources-> input.txt

Note that src and test are in the same hierarchy.

public class MyFileReaderTest
{

  ClassLoader classLoader = getClass().getClassLoader();

  @Test
  public void testReadInputFile() throws Exception
  {
    String file = classLoader.getResource("test/com/au/myapp/resources/input.txt").getFile();
    List<String> result = InputFileReader.getInstance().readFile(file);
    assertEquals("Size of the list should be 2", 2, result.size());
  }
}

Classloader.getResource() returns null. Really appreciate your assistance.

like image 651
Anuruddha Avatar asked Dec 15 '22 02:12

Anuruddha


1 Answers

The classloader uses the classpath to load resources. Your classes are, most probably, in the package com.au.myapp.util. Not in the package test.com.au.myapp.util.

The directory structure matched the package structure. That means that the directories src and test are both source roots.

Since your file is in the directory com/au/myapp/resources under a source root, its package is com.au.myapp.resources.

So you need

classLoader.getResource("com/au/fitbits/resources/input.txt");

This is a resource, loaded from the classpath. It might be a file now, because you're in development mode, and classes are loaded directly from the file system. But once in production, they won't be loaded from the file system anymore, but from a jar file. So you can't use file IO to read the content of this resource. So use

classLoader.getResourceAsStream("com/au/fitbits/resources/input.txt")

and read from this stream.

like image 162
JB Nizet Avatar answered Dec 24 '22 08:12

JB Nizet