The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →In Cucumber for the JVM, annotations connect Java glue code to Gherkin steps and scenario lifecycle events. Use @Given, @When and @Then to implement steps readers can see in a feature; use @Before and @After for technical setup and cleanup; and reserve step hooks for cross-cutting work such as instrumentation. This guide covers the Java API and JVM behavior, not every Cucumber language implementation.
How Java step definitions map to Gherkin
A step definition is glue: a Java method annotated with a Cucumber expression that matches the text of a Gherkin step. Cucumber loads the glue, matches each step at runtime, converts captured values to supported parameter types, and invokes the matching method. The Gherkin keyword communicates the step’s role to readers; matching is against the step text after the keyword.
For example, a feature can describe behavior in business-readable terms:
Feature: Basket count
Scenario: A shopper sees a basket count
Given I have 2 items in my basket
When I open the basket
Then I should see 2 items
A Java step definition can bind the first step and receive its integer argument:
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import io.cucumber.java.en.Given;
public class BasketSteps {
@Given("I have {int} items in my basket")
public void haveItemsInBasket(int count) {
// Establish the test state using the application's test interface.
}
}
The current Java package for this annotation is io.cucumber.java.en.Given. Use the corresponding When and Then annotations for the other step roles. Keep expressions specific: overlapping expressions can cause ambiguity when more than one definition matches a step.
What belongs in Given, When and Then
- Given establishes a known precondition or state.
- When describes an event or interaction.
- Then expresses the expected outcome.
These roles help keep scenarios useful as executable specifications. Avoid packing a scenario with implementation details that hide the behavior it is meant to describe.
Step definitions versus hooks
Step definitions implement the steps written in feature files. Hooks run at lifecycle points without appearing as Gherkin steps. That makes hooks convenient for infrastructure, but it also means feature readers may not see important setup unless it is documented or expressed in the scenario.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
| Approach | Scope | Visibility | Best fit and trade-off |
|---|---|---|---|
Background or a Given step |
Feature background or an explicit scenario step | Visible in the feature | Business-relevant context readers need to understand; adds explicit feature text, which clarifies the precondition. |
@Before or @After |
Scenario lifecycle | Hidden from feature readers | Reusable technical setup and cleanup; concise, but important behavior can be obscured if placed here. |
@BeforeStep or @AfterStep |
Individual step lifecycle | Hidden from feature readers | Cross-cutting instrumentation; fine-grained, but can add execution noise and make scenarios harder to follow. |
As Cucumber’s reference puts it, “Whatever happens in a Before hook is invisible to people who only read the features.” Put meaningful business context in a Background or Given step. Use hooks for low-level work such as starting a browser or clearing test data.
Free tools Windows power users keep installed
One-click scans. No signup required.
Scenario hooks: setup, cleanup and tag filtering
@Before runs before a scenario’s first step. @After runs after its last step, including when the scenario has a failed, undefined, pending or skipped outcome. A hook may accept a Scenario parameter when it needs to inspect scenario information, such as status.
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.Scenario;
public class BrowserHooks {
@Before
public void startBrowser() {
// Start low-level browser test infrastructure.
}
@After
public void stopBrowser(Scenario scenario) {
// Use scenario information for cleanup or failure diagnostics.
// Release resources even when a scenario did not pass.
}
}
The example shows lifecycle placement, not a complete browser-driver integration; the driver, reporting setup and resource-management strategy depend on your test stack. Keep cleanup safe when setup was incomplete, so a setup failure does not cause a second failure during teardown.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Limit a hook with a tag expression
A hook’s source-file location does not restrict which scenarios it applies to. Use a tag expression when only some scenarios should run the hook. For example, a browser setup hook can be limited to scenarios tagged @browser and excluded from those tagged @headless:
import io.cucumber.java.Before;
public class BrowserHooks {
@Before(value = "@browser and not @headless")
public void startBrowser() {
// Browser-only setup.
}
}
Tags belong on features, rules or scenarios, not above a Background or on individual steps. Choose tags to express scenario selection, rather than relying on where a hook class happens to live.
Ordering hooks
The Java API supports an explicit order value, for example @Before(order = 10). Before hooks run in declaration order in the implementations described by the reference. Do not assume teardown order from setup order: after-hook ordering can differ across implementations and older materials. Check the current Java API for the Cucumber version in your project before depending on teardown sequencing.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Step hooks and run-wide hooks
@BeforeStep and @AfterStep wrap individual steps. Cucumber describes this as invoke-around behavior: when a BeforeStep hook runs, its AfterStep counterpart also runs regardless of that step’s result. After a step does not pass, subsequent steps and their hooks are skipped. This makes step hooks suitable for cross-cutting logging or instrumentation, but not a good place for application behavior that should be visible in the scenario.
BeforeAll and AfterAll run once around the full scenario run in the API reference. They are run-wide lifecycle hooks, not substitutes for scenario-level setup. If your suite depends on shared state, take care to manage it explicitly rather than assuming scenario isolation applies to run-wide work.
State sharing and dependency injection on the JVM
Cucumber’s JVM state guidance says it creates a new instance of each glue class before each scenario. This gives glue instances scenario scope by default: mutable instance fields do not automatically carry over as the same object into the next scenario.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
If step definitions and hooks need the same collaborators within a scenario, use a supported dependency-injection module to organize and share those objects. The listed options include PicoContainer, Spring, Guice, OpenEJB, Weld, Needle and Quarkus. PicoContainer is the suggested starting point when the application does not already use another DI module. A DI module is not required simply because glue classes exist; classes with empty constructors need no constructor injection.
Avoid mutable static fields as a shortcut for sharing scenario data. Static state can outlive a scenario and make results depend on execution order or parallelism. Keep scenario data in scenario-scoped objects, and consult current installation guidance for the dependency coordinates and runner setup that match your Cucumber and test-platform versions.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Browser screenshots for Cucumber failure diagnostics
In browser-based scenarios, a screenshot can help explain what the application displayed when a test failed. The hook can decide whether to collect diagnostics from the scenario status, but the browser driver and report attachment mechanism are specific to your integration. Do not assume that a Cucumber Scenario object can capture a browser image by itself; connect the hook to the browser and reporting APIs used by your project.
Or skip the browser setup
If you need a rendered page screenshot rather than a browser-driver integration in the test, ScreenshotNeo offers a one-request screenshot API. For example, capture a URL as WebP:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request options. ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; those steps can each be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.
Sign up for 1,000 free screenshots a month, with no card required.
Troubleshooting annotation and hook behavior
- A step is undefined: Check that its text after the Gherkin keyword matches a registered expression, that the Java glue package is included in the runner’s glue configuration, and that the definition uses the Java annotation package. Add a definition or correct the expression; do not expect the keyword itself to be part of the match.
- A step is ambiguous: More than one expression may match. Make expressions more specific or consolidate overlapping definitions so one step maps to one intended method.
- A hook runs for an unexpected scenario: File location alone does not set scope. Add or correct the hook’s tag expression and verify the scenario tags.
- Cleanup does not run where expected: Confirm it is an
@Afterhook rather than code placed only after a successful step. After hooks run after scenario outcomes that include failed, undefined, pending or skipped steps. - Later steps or step hooks do not run: A preceding step did not pass. Cucumber skips subsequent steps and their hooks after that outcome; put diagnostics in lifecycle code that does run, rather than relying on a later step.
- State leaks between scenarios: Check for mutable static fields, external test data, or run-wide hooks. Use scenario-scoped glue and an appropriate DI module for collaborators that must be shared within one scenario.
- Hook ordering causes flaky teardown: Do not infer After ordering from Before ordering. Verify the Java API behavior for the exact version in use and make teardown robust to partially initialized resources.
Version and implementation scope
These examples target Cucumber for Java on the JVM and use the current-style io.cucumber.java annotation packages. Hook behavior can vary among Cucumber language implementations, and runner configuration depends on the Java test platform and project version. This guide does not prescribe Maven or Gradle coordinates or a JUnit runner setup; use installation instructions matching the versions already selected for your project.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute

