-2
  1. Summarize the problem:

I'm testing a Spring-Rest/MVC-Api (without Spring-Boot) with JUnit 5. I have a class CatRepositoryBackUpRepo, i read and write a file there that i link with private File datei = new File("Cats.json");. This file is in src/main/resource. This works fine when i run the program. I checked it with the println-Logging-Text. When i want to test this read-method in a Junit-test-Class (link at the end), it didn't find the file, and throw a file not found exception.

  1. Describe what you’ve tried:

I created a /src/test/resource-folder and place the same file there, but didnt worked. Then i used the test-class to write such a file and it was placed on the same level as the /src-Folder and the pom.xml, on the project-path. It seems that the property for the resource-path when running the testclass is the problem, but i dont know how to fix it, how to tell the class-under-test the correct property. I run the test-cases with Junit in a IntelliJ Ultimate Edit., the working directory of the run-configuration for Junit is set to $MODULE_WORKING_DIR$.

  1. Add some code

This is the class under test, with the method under test readCats() https://github.com/IngmarEckhardt/RestControl/blob/master/src/main/java/de/cats/restcat/service/CatRepositoryBackupRepo.java

And this is the test-class, the only method that doesnt worked is readCats_withHDDready_shouldReturnArrayList()

https://github.com/IngmarEckhardt/RestControl/blob/master/src/test/java/de/cats/restcat/service/CatRepositoryBackupRepoTest.java

  • Hey welcome on SO. Keep in mind to use the search function first before asking questions. Searching for your problems I found some sites that might help you and understand the problem better and your suggested solution since it is not optimal. https://stackoverflow.com/questions/40710420/reading-a-resource-file-in-junit-test , https://stackoverflow.com/questions/28673651/how-to-get-the-path-of-src-test-resources-directory-in-junit , https://stackoverflow.com/questions/7613359/why-cant-i-access-src-test-resources-in-junit-test-run-with-maven – Nopileos Sep 25 '21 at 18:48
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 29 '21 at 03:53

1 Answers1

-2

I solved the problem by myself, but i will share the solution if anybody search for it.

The problem was, that the spring-mvc-Framework uses a Classloader to get resources from the classpath, and this classloader is behind the scene invoked with the call for new File("Cats.json").

But obviously this doesn't work out with the test-class. I call the Classloader now explicit with

ClassLoader classLoader = getClass().getClassLoader();
File datei = new File(classLoader.getResource("Cats.json").getFile());

instead of just using

File datei = new File("Cats.json");

This solved my problem.

Nopileos
  • 1,976
  • 7
  • 17