让Eclipse使用src/test/resources而不是src/main/resources

12
我正在Eclipse中编写一个小的Maven应用程序。我将一些属性文件和我的应用程序上下文存储在src/main/resources目录中。
现在我想让Eclipse使用位于src/test/resources目录中的属性。因此,当我在Eclipse中运行和调试程序时,应该使用这些测试属性。
你知道如何实现这个吗?

它会自动完成这个过程。你是怎么读取它们的? - Bozho
我在应用程序上下文XML中使用以下代码读取属性文件:<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="db.properties" /></bean> - user321068
4个回答

14

请尝试以下方法:

  1. 进入“运行->运行配置…”(如果是调试则为“运行->调试配置…”)
  2. 打开你正在使用的运行(调试)配置文件
  3. 打开“Classpath”选项卡
  4. 选择“用户条目”,并点击右侧的“高级…”
  5. 在打开的窗口中选择“添加文件夹”,指向你的src/test/resources文件夹
  6. 这个文件夹将出现在“用户条目”下面,然后你应该将它移到第一位成为classpath中的第一个条目

1
src/main/resources在类路径上位于src/test/resources之前。因此,你的db.properties文件从src/main/resources中加载。 - yatskevich
谢谢你的回答,它对我很有帮助!对我来说,确切的点击路径是(可能是Eclipse的新版本?):菜单“Run”->选择“Run configurations...”->选择“Dependencies”选项卡->在树中选择“Classpath entries”->单击[高级...]按钮->从单选组中选择“添加文件夹”->单击[确定]按钮。 - EternalBeginner
我的使用方式告诉我,我确实在构建中缺少一个文件夹。但最终并不需要配置额外的文件夹。我在创建测试文件夹中的“资源”文件夹时打了一个错别字,因此maven不知道我的错误命名的文件夹。当我更正了错别字后,maven可以识别该文件夹,然后我可以使用:在项目上下文菜单中->“Maven”->“更新项目…”,并且为了安全起见:菜单“项目”->“清理…”。这已经足够了,即使没有在运行配置中配置额外的文件夹。 - EternalBeginner

6

无论您使用Maven Eclipse插件还是m2eclipsesrc/test/resources在类路径上(更准确地说,它们的输出目录)优先于src/main/resources。换句话说,无需操作,一切都像在命令行上一样正常工作。


3
使用测试覆盖(例如testOverrides.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!--  this file need to be imported before other contexts to ensure the test properties take effect -->

    <context:property-placeholder location="classpath*:META-INF/spring/testproperties/*.properties"/>

</beans>

在您的测试中,请确保首先导入它:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:META-INF/spring/testOverrides.xml","classpath*:META-INF/spring/applicationContext.xml"})
public class SomeTest { ... }

现在将所有测试属性放在src/test/resources/META-INF/spring/testproperties/中。

您还需要确保main占位符配置器永远不会看到testproperties,例如这是我的:

<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>

它不使用双星号通配符,因此只会查看该目录。

我使用上述方法非常成功。


1

在Eclipse 2021中进行了测试。转到“运行配置”(或调试)并转到“类路径”选项卡。现在,您可以选择检查或取消检查,具体取决于您是否想使用/src/main/resources或/src/test/resources,如下所示:

enter image description here

最后,应用并运行您的程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接