Get list of activated profile name at run time in maven java project

I need to be able to use a profile activated during the execution time of JUnit tests. I was wondering if there is a way to do something like:

String str = System.getProperty("activated.profile[0]");

Or any other relative way ...

I realized that it is possible to use ${project.profiles[0].id}bu, somehow it does not work.

Any ideas?

+11
source share
2 answers

When using surefire to run unit tests, it usually starts a new JVM to run tests, and we need to pass information to the new JVM. This can usually be done using the "systemPropertyVariables" tag.

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>  

unit test :

/**
 * 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

+15

pom:

<profiles>
    <profile>
        <id>a-profile-id</id>

        <properties>
            <flag>a-flag-value</flag>
        </properties>
    </profile>
</profiles>

java:

String flagValue = System.getenv("flag");
0

Source: https://habr.com/ru/post/1622350/


All Articles