如何在运行时从CustomCucumber.java获取Maven执行ID?
Great question! Let’s break this down clearly for you:
Short Answer
Unfortunately, you can’t directly read the Maven execution ID (execId) from your CustomCucumber runner class at runtime without explicitly passing it via a system property or Maven parameter.
Why Direct Access Isn’t Possible
Maven’s plugin execution IDs are part of your build configuration (stored in pom.xml) that Maven processes during the build phase. When the Failsafe plugin launches your integration tests (like LauncherIT), it spins up a completely separate JVM for the test suite. This test JVM has no direct connection to Maven’s internal build context or metadata—including execution IDs.
Your custom Cucumber runner runs entirely within this isolated test environment, which only gets access to the environment variables, system properties, and classpath that Maven explicitly passes to it. There’s no built-in bridge between Maven’s build-time configuration and the test runtime that exposes execution IDs natively.
The Practical Workaround: Pass the Execution ID via System Property
Since direct access isn’t feasible, the standard and reliable workaround is to inject the execution ID as a system property in your plugin configuration, then read it in your CustomCucumber class. Here’s how to set it up:
Step 1: Update Your Failsafe Execution in pom.xml
Add a systemPropertyVariables block to pass the execution ID using Maven’s built-in ${execution.id} placeholder (which automatically resolves to the current execution’s ID):
<execution> <id>execId</id> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> <configuration> <includes> <include>**/*LauncherIT.java</include> </includes> <!-- Inject execution ID as a system property --> <systemPropertyVariables> <maven.execution.id>${execution.id}</maven.execution.id> </systemPropertyVariables> </configuration> </execution>
Step 2: Read the System Property in CustomCucumber
In your custom runner class, fetch the system property at runtime:
public class CustomCucumber extends Cucumber { public CustomCucumber(Class<?> clazz) throws InitializationError { super(clazz); // Retrieve the execution ID from system properties String executionId = System.getProperty("maven.execution.id"); if (executionId != null) { // Use the ID for your custom logic System.out.println("Current Maven Execution ID: " + executionId); } } }
Wrap-Up
While direct access to the Maven execution ID from the test runtime isn’t supported, using system properties is a clean, maintainable way to share this build-time metadata with your custom Cucumber runner. It’s the standard approach recommended for passing build configuration to test code in Maven.
内容的提问来源于stack exchange,提问作者RedMurloc

