[java] Resource files not found from JUnit test cases

Summary

My JUnit tests are not finding the files they require during execution. I'm using Maven for dependency management and compilation.

Details

All files required by the test cases are located in: src/test/resources.

For example, src/test/resources/resourceFile.txt.

To access a resource I use the following code:

URL url = getClass().getResource("/resourceFile.txt").getFile();
File file = new File(url);

But then file.exists() returns false. And the error I get is:

Tests in error: 
  myJUnitTestCase(tests.MyJUnitTestClass): /home/me/workspace/Project%20Name/target/test-classes/resourceFile.txt (No such file or directory)

Note, the following gives the same error (notice the removed / prefix):

URL url = getClass().getClassLoader().getResource("resourceFile.txt").getFile();
File file = new File(url);

It seems as though the files from src/test/resources are not getting copied into target/test-classes.

Any ideas?

The following questions did not help

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

Loading Properties File In JUnit @BeforeClass

How to deal with the test data in Junit?

Software Versions

Ubuntu 12.04

Apache Maven 2.2.1

Java 1.7.0

Eclipse (Java EE IDE for Web Developers) Indigo Service Release 2

(truncated) Maven POM

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.groupId</groupId>
    <artifactId>artifactId</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>name</name>
    <build>
        <finalName>name</finalName>
        <directory>target</directory>
        <outputDirectory>target/classes</outputDirectory>
        <testOutputDirectory>target/test-classes</testOutputDirectory>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

This question is related to java unit-testing maven junit resourcebundle

The answer is


My mistake, the resource files WERE actually copied to target/test-classes. The problem seemed to be due to spaces in my project name, e.g. Project%20Name.

I'm now loading the file as follows and it works:

org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);

Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):

myClass().getResource("resourceFile.txt")??.toURI();

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue


The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.

String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());

System.out.println(file.getAbsolutePath());

Note : Here the sample.txt file should be placed under src/test/resources folder.

For more details refer options_to_load_test_resources


This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.

You can verify that by checking your effective POM using this command

mvn help:effective-pom

    <finalName>name</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.

    <resources>
        <resource>
            <directory>/home/josh/desktop/app_resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>/home/josh/desktop/test_resources</directory>
        </testResource>
    </testResources>

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.

    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to unit-testing

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to test the type of a thrown exception in Jest Unit Tests not discovered in Visual Studio 2017 Class Not Found: Empty Test Suite in IntelliJ Angular 2 Unit Tests: Cannot find name 'describe' Enzyme - How to access and set <input> value? Mocking HttpClient in unit tests Example of Mockito's argumentCaptor How to write unit testing for Angular / TypeScript for private methods with Jasmine Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Examples related to maven

Maven dependencies are failing with a 501 error Why am I getting Unknown error in line 1 of pom.xml? Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Unable to compile simple Java 10 / Java 11 project with Maven ERROR Source option 1.5 is no longer supported. Use 1.6 or later 'react-scripts' is not recognized as an internal or external command How to create a Java / Maven project that works in Visual Studio Code? "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Examples related to junit

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to resolve Unneccessary Stubbing exception JUnit 5: How to assert an exception is thrown? How do I mock a REST template exchange? Class Not Found: Empty Test Suite in IntelliJ Unable to find a @SpringBootConfiguration when doing a JpaTest Failed to load ApplicationContext (with annotation) Example of Mockito's argumentCaptor Mockito - NullpointerException when stubbing Method Spring jUnit Testing properties file

Examples related to resourcebundle

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US Format a message using MessageFormat.format() in Java Resource files not found from JUnit test cases How to use UTF-8 in resource properties with ResourceBundle How to load a resource bundle from a file resource in Java?