Search code examples
javaspringspring-bootresourcessts

Not able to read resource files from src/test/resources in STS


I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json.

Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:

public class CommonTestUtility {
    
    public static String getFileAsString(String fileName) throws IOException {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        File file = new File(classLoader.getResource(fileName).getFile());
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }
}

Now while calling this function as

class ServerTest {
@Test
void test_loadResource() {
    String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}

}

, It's giving me the error as:

CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.

I tried to include the src/test/resources/ in the run configuration of Junit ServerTest.java, but still it's not able to find out the resource How to resolve this issue?


Solution

  • I recreated the same scenario you describe and your code works for me. Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.

    My Project