Reputation: 111
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
Reputation: 279
Depending on your IDE it is possible that your resource directory is not in the classpath.
In IntelliJ:
In Eclipse:
Upvotes: 2
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