【发布时间】:2018-05-29 16:22:42
【问题描述】:
我正在尝试使用位于 src/test/resources 下的文件进行单元测试,但是当我尝试读取它时,我无法始终获得空指针。
我正在使用带有 JDK 10 和 Gradle 的 Spring Boot 2.0.2。
我尝试了在谷歌上搜索问题时发现的许多代码变体,但都没有成功。
我的 build.gradle 看起来像这样:
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')
}
我的测试是这些行的一些变体(我尝试过的都没有成功):
@Test
public void isSortedCorrectly() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("test-file.json").getFile()); // java.lang.NullPointerException
}
测试类在这里:
src\test\java\com\moc\omc\x\y\MyUnitTest.java
测试文件在这里:
src\test\java\resources\test-file.json
【问题讨论】:
-
您需要
File,还是可以使用InputStream?因为您无法通过ClassLoader.getResource可靠地加载文件。另外,在文件名前加上/。 -
我无法让它工作。它似乎引用了
src/main/.../resources而不是src/test/resources。如果我运行这段代码,它会给我src/main/.../resources文件夹中的文件。