javamavenunit-testingmaven-profilessystem-variable

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


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

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

Or any other relative way...

I realized there is an option to use ${project.profiles[0].id} bu somehow it's not working.

Any ideas?


Solution

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

    I was able to exercise this using a quickstart Java project, where I added this to the POM:

    I declared the following profiles

    <profiles>
        <profile>
            <id>special-profile1</id>
        </profile>
        <profile>
            <id>special-profile2</id>
        </profile>
    </profiles>     
    

    And this to surefire configuration:

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

    And in my unit test, I added this:

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        System.out.println("Profile ID:  " + System.getProperty("profileId"));
    }
    

    When invoking the "test" command without profile (i.e. using mvn test), I got this:

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

    And we I used mvn -P special-profile2 test, I got this

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

    This will pass along the name of the first active profile. If we have potentially more than one active profiles, then we will probably need to use more system properties.

    Note: I tested this using Maven 3.1.1