How to Get the Path of Src/Test/Resources Directory in Junit

JUNIT not identifying resources under src/test folder

you can use classLoader like this :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

Regards.

Why Can't I access src/test/resources in Junit test run with Maven?

Access MainConfig.xml directly. The src/test/resources directory contents are placed in the root of your CLASSPATH.

More precisely: contents of src/test/resources are copied into target/test-classes, so if you have the following project structure:

.
└── src
└── test
├── java
│   └── foo
│   └── C.java
└── resources
├── a.xml
└── foo
└── b.xml

It will result with the following test CLASSPATH contents:

  • /foo/C.class
  • /a.xml
  • /foo/b.xml

To actually access the files from Java source, use
getClass().getResource("/MainConfig.xml").getFile().

Java path to file in src/main/resources

The problem was that I have not included the resource in the maven build in pom file. When I included the following it worked with abcManager.class.getResource("/abc.access")

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>abc.access</include>
</includes>
</resource>
</resources>
</build>

Unable to access test resources from junit tests

Alright so Timo was able to figure it out. I hadn't rebuilt the project for a while (:facepalm:). Coming from the python world here, where things are a little different. Thanks for working through this with me everyone, it really means a lot!

file not found on path src/test/resources/

You should never depend on File. Load InputStream from classpath.

Both src/main/resources and src/test/resources are in the classpath if you use the Maven standard directory structure.

I tend to like the Apache Commons IO library and Spring ClassPathResource.



Related Topics



Leave a reply



Submit