在 maven java 项目中的运行时获取激活的配置文件名称的列表
2022-09-03 14:35:56
我需要能够使用在 JUnit 测试运行时激活的配置文件。我想知道是否有任何方法可以做这样的事情:
String str = System.getProperty("activated.profile[0]");
或任何其他相对方式...
我意识到有一个选项可以使用bu,不知何故它不起作用。${project.profiles[0].id}
有什么想法吗?
我需要能够使用在 JUnit 测试运行时激活的配置文件。我想知道是否有任何方法可以做这样的事情:
String str = System.getProperty("activated.profile[0]");
或任何其他相对方式...
我意识到有一个选项可以使用bu,不知何故它不起作用。${project.profiles[0].id}
有什么想法吗?
当使用 surefire 运行单元测试时,它通常会生成一个新的 JVM 来运行测试,并且我们必须将信息传递给新的 JVM。这通常可以使用“systemPropertyVariables”标签来完成。
我能够使用快速入门Java项目来练习这一点,在那里我将其添加到POM中:
我声明了以下配置文件
<profiles>
<profile>
<id>special-profile1</id>
</profile>
<profile>
<id>special-profile2</id>
</profile>
</profiles>
这是肯定的配置:
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<systemPropertyVariables>
<profileId>${project.activeProfiles[0].id}</profileId>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
在我的单元测试中,我添加了以下内容:
/**
* Rigourous Test :-)
*/
public void testApp()
{
System.out.println("Profile ID: " + System.getProperty("profileId"));
}
当在没有配置文件的情况下调用“test”命令(即使用)时,我得到了这个:mvn test
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.fxs.AppTest Profile ID: development Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec - in com.fxs.AppTest Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
我们我用过,我得到了这个mvn -P special-profile2 test
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.fxs.AppTest Profile ID: special-profile2 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec - in com.fxs.AppTest Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
这将传递第一个活动配置文件的名称。如果我们可能有多个活动配置文件,则可能需要使用更多的系统属性。
注意:我使用 Maven 3.1.1 对此进行了测试
我接下来在pom文件中使用的其他案例:
<profiles>
<profile>
<id>a-profile-id</id>
<properties>
<flag>a-flag-value</flag>
</properties>
</profile>
</profiles>
和在java中:
String flagValue = System.getenv("flag");