Why Can#39;t I access src/test/resources in Junit test run with Maven?(为什么我无法在使用 Maven 的 Junit 测试运行中访问 src/test/resources?)
问题描述
我在运行以下代码时遇到问题:
I am having a problems running the following code:
configService.setMainConfig("src/test/resources/MainConfig.xml");
从 Junit @Before 方法中.
From within a Junit @Before method.
这是 Maven 构建其目标文件夹的方式吗?
Is this the way Maven builds out its target folder?
推荐答案
直接访问MainConfig.xml
.src/test/resources
目录内容放置在您的 CLASSPATH 的根目录中.
Access MainConfig.xml
directly. The src/test/resources
directory contents are placed in the root of your CLASSPATH.
更准确地说:src/test/resources
的内容被复制到target/test-classes
中,所以如果你有以下项目结构:
More precisely: contents of src/test/resources
are copied into target/test-classes
, so if you have the following project structure:
.
└── src
└── test
├── java
│ └── foo
│ └── C.java
└── resources
├── a.xml
└── foo
└── b.xml
它将产生以下测试 CLASSPATH 内容:
It will result with the following test CLASSPATH contents:
/foo/C.class
/a.xml
/foo/b.xml
要真正从 Java 源访问文件,请使用getClass().getResource("/MainConfig.xml").getFile()
.
To actually access the files from Java source, use
getClass().getResource("/MainConfig.xml").getFile()
.
这篇关于为什么我无法在使用 Maven 的 Junit 测试运行中访问 src/test/resources?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我无法在使用 Maven 的 Junit 测试运行中访问 src/test/resources?


基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01