To implement a Test Runner class with JUnit in Cucumber, you need to create a class annotated with @RunWith and @CucumberOptions. This class serves as the entry point for running your Cucumber test scenarios written in .feature files using JUnit.
Below are the steps to implement Test runner in Cucumber with Testng
1. Add Maven Dependencies
Make sure your pom.xml contains these dependencies:
<dependencies> <!-- Cucumber JUnit --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit</artifactId> <version>7.11.1</version> <scope>test</scope> </dependency> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- Cucumber Java --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <version>7.11.1</version> </dependency> </dependencies>
2. Create Feature File
Example: src/test/resources/features/login.feature
Feature: Login functionality Scenario: Valid login Given user is on login page When user enters valid username and password Then user is navigated to the homepage
3. Create Step Definition File
Example: src/test/java/stepdefinitions/LoginSteps.java
package stepdefinitions; import io.cucumber.java.en.*; public class LoginSteps { @Given("user is on login page") public void user_is_on_login_page() { System.out.println("User is on login page"); } @When("user enters valid username and password") public void user_enters_valid_username_and_password() { System.out.println("User enters credentials"); } @Then("user is navigated to the homepage") public void user_is_navigated_to_the_homepage() { System.out.println("User navigated to homepage"); } }
4. Create Test Runner Class
Example: src/test/java/testrunner/TestRunner.java
package testrunner; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) // Tells JUnit to run Cucumber tests @CucumberOptions( features = "src/test/resources/features", // path to feature files glue = "stepdefinitions", // package of step definitions plugin = {"pretty", "html:target/cucumber-reports.html"}, monochrome = true ) public class TestRunner { // No code needed here }
5. Run the Test
You can run the TestRunner.java file like a normal JUnit test class. Cucumber will pick the .feature files and corresponding step definitions.
Important Points:
| Component | Description |
|---|---|
| @RunWith(Cucumber.class) | Instructs JUnit to use Cucumber's test runner |
| @CucumberOptions | Provides feature path, glue (steps), plugin, formatting |
| features | Path to .feature files |
| glue | Package containing step definition files |
| plugin | Reporting output (HTML, JSON, etc.) |
| monochrome | Makes console output more readable |