IntelliJ中如何通过Gherkin Language依次运行两个Java类?
Hey there! Great question—you don't actually need to write a third Java class to run your two Cucumber test classes sequentially. Let me walk you through a few straightforward solutions tailored to IntelliJ and Cucumber workflows:
1. Run Directly via IntelliJ's Feature File Selection
The simplest way is to leverage IntelliJ's built-in Cucumber support:
- Navigate to your Project view and find the two
.featurefiles linked to your Java classes. - Hold
Ctrl(Windows/Linux) orCmd(Mac) to select both files at once. - Right-click the selected files and choose Run 'feature1.feature, feature2.feature' from the menu.
IntelliJ will automatically execute the tests for each feature in the order you selected them.
2. Create a Reusable Combined Cucumber Run Configuration
For a setup you can reuse anytime:
- Open the Run/Debug Configurations window (click the dropdown next to the run button and select Edit Configurations...).
- Click the
+icon in the top-left and choose Cucumber Java. - In the Configuration tab:
- Set the Glue field to the package where your two test classes live (e.g.,
com.yourteam.tests). - In Feature paths, click
+and add either the parent folder containing both.featurefiles, or select each file individually.
- Set the Glue field to the package where your two test classes live (e.g.,
- Name the configuration (like "Run All Cucumber Tests") and click Apply.
Now you can run this configuration whenever you need to execute both test classes in sequence.
3. Use a Test Suite Class (For Strict Order/Dependencies)
If your tests require a specific execution order (e.g., one must run before the other), you can create a lightweight suite class (this is optional):
JUnit 5 Suite Example:
import org.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; @Suite @SelectClasses({FirstDatabaseTest.class, SecondDatabaseTest.class}) public class AllTestsSuite { // No code needed here—this class just acts as a test container }
- Replace
FirstDatabaseTest.classandSecondDatabaseTest.classwith your actual test class names. - Right-click the suite class and select Run 'AllTestsSuite'—tests will run in the order listed in
@SelectClasses.
4. Build Tool Command Line (Maven/Gradle)
If you use Maven or Gradle, run all tests with a single command:
- For Maven: Run
mvn testin your project root. Maven will automatically scan and execute all test classes matching the default pattern (e.g.,*Test.java). - For Gradle: Run
gradle test—Gradle will do the same, running all tests in your project.
Key Takeaway
You only need a third class if you require strict custom ordering or want a reusable test group. For most cases, the first two IntelliJ-based methods are faster and simpler.
内容的提问来源于stack exchange,提问作者Rita Alves

