Magnus
Magnus

Reputation: 111

Can't jUnit test with file from resources folder

I'm trying to unit test with a file located under src/test/resources, but I can't always get a nullpointer when I'm trying to read it.

I'm using Spring Boot 2.0.2, with JDK 10 and Gradle.

I've tried many variants of code found when googeling the problem, but I have no success.

My build.gradle looks like this:

buildscript {
     ext {
        springBootVersion = '2.0.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.moc.omc'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 10

repositories {
    mavenCentral()
    jcenter()
}
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-devtools")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("javax.xml.bind:jaxb-api:2.3.0")
    compile("com.h2database:h2")
    compile("io.springfox:springfox-swagger2:2.9.0")
    compile("io.springfox:springfox-swagger-ui:2.9.0")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

My test is some variant of these lines (nothing I've tried has had any success):

@Test
public void isSortedCorrectly() throws IOException {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("test-file.json").getFile()); // java.lang.NullPointerException
}

The test class is here:

src\test\java\com\moc\omc\x\y\MyUnitTest.java

The test file is here:

src\test\java\resources\test-file.json

Upvotes: 3

Views: 7316

Answers (2)

Kris Wheeler
Kris Wheeler

Reputation: 279

Depending on your IDE it is possible that your resource directory is not in the classpath.

In IntelliJ:

  1. Right-click your test/resources (or test/java/resources) directory
  2. Select the "Mark Directory as..." sub-menu
  3. Select "Test Resources Root"
  4. This directory will appear with a decorator graphic symbolizing that it is in the classpath

In Eclipse:

  1. Go to "Run->Run configurations..." (in case of debug "Run->Debug configurations...")
  2. Open Run (Debug) configuration which you use
  3. Open "Classpath" tab
  4. Select "User Entries" and click "Advanced..." on the right
  5. In the opened window select "Add folder", point to your src/test/resources
  6. This folder will appear under "User entries", then you should move it up to make it the first on your classpath

Upvotes: 2

lance-java
lance-java

Reputation: 27958

The file needs to be at

src\test\resources\test-file.json

Instead of

src\test\java\resources\test-file.json 

Upvotes: 3

Related Questions