gpt4 book ai didi

java - 无法使用资源文件夹中的文件进行 jUnit 测试

转载 作者:行者123 更新时间:2023-11-29 04:18:44 24 4
gpt4 key购买 nike

我正在尝试对位于 src/test/resources 下的文件进行单元测试,但是当我尝试读取它时,我不能总是得到一个空指针。

我正在使用 Spring Boot 2.0.2,以及 JDK 10 和 Gradle。

在谷歌搜索问题时,我尝试了很多代码变体,但都没有成功。

我的 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

最佳答案

文件需要在

src\test\resources\test-file.json

代替

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

关于java - 无法使用资源文件夹中的文件进行 jUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50588869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com