Cucumber-JVM中@After钩子执行两次问题求助
Hey there, let's dig into the issues you're facing with Cucumber and TestNG—they're likely connected, so we'll tackle them together:
1. Root Cause Link Between All Your Issues
The "Multiple Definitions" warning for your step Volare Collector Home Page opens in browser is the key here. When Cucumber detects duplicate step definitions, it can end up loading your step classes multiple times, which explains both the duplicate class names in your test report and the @After hook running twice.
2. Step-by-Step Fixes
Check for Duplicate Step Definitions
- Do a full search across your codebase for the exact step text
Volare Collector Home Page opens in browser. Look for:- Identical
@Given/@When/@Thenannotations in different step classes (e.g.,HomePageSteps.javaandCollectorSetupSteps.javaboth defining the same step) - Accidental duplicate method definitions within the same step class (you might have copied a method and forgot to modify the step text)
- Identical
- Delete or merge the duplicate definitions—keep only one valid implementation of the step.
Validate Cucumber Glue Configuration
- If you're using
@CucumberOptionsin your TestNG runner class, make sure thegluepath isn't redundant. For example:
❌ Bad:@CucumberOptions(glue = {"com.yourpackage.steps", "com.yourpackage.steps.home"})(subpackage is already covered by the parent)
✅ Good:@CucumberOptions(glue = {"com.yourpackage.steps"}) - Also check your TestNG suite XML file—avoid adding the same Cucumber runner class multiple times, or configuring glue both in the XML and the runner annotation (this can cause double-scanning).
Clean Up Build Files & Duplicate Runner Classes
- Old compiled files in your
target/outdirectory can sometimes cause Cucumber to load stale classes. Do a full clean build of your project to wipe these out. - Ensure you don't have multiple Cucumber runner classes (e.g.,
RunCucumberTests.javain two different packages) that are both being picked up by TestNG.
Verify @After Hook Scope
- Make sure you haven't added the
@Afterhook to multiple step classes. Each class with an@Afterhook will execute it once per scenario, so if two classes have the hook, you'll see it run twice. - Double-check that you're not mixing up Cucumber hooks:
@After(runs after each scenario) vs@AfterStep(runs after each step)—though this is less likely to cause your specific issue.
3. Quick Test to Confirm Fix
After making these changes, run your single feature file again. The "Multiple Definitions" warning should disappear, the test report will show only one instance of your step class, and the @After hook will execute exactly once per scenario.
内容的提问来源于stack exchange,提问作者Ivan

