To integrate Selenium, Cucumber, and JUnit, you can build a Behavior Driven Development (BDD) test framework that allows you to define test scenarios in Gherkin (plain English), implement those steps in Java (using Selenium for UI interactions), and execute them using JUnit.
Components Overview:
| Component | Role |
|---|---|
| Selenium WebDriver | Automates browser actions |
| Cucumber | Provides BDD support via .feature files |
| JUnit | Executes the test suite (test runner) |
Below are the steps to integrate Selenium, Cucumber and JUnit
1. Maven Dependencies
<dependencies> <!-- Selenium --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.19.1</version> </dependency> <!-- Cucumber --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <version>7.14.0</version> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit</artifactId> <version>7.14.0</version> <scope>test</scope> </dependency> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
2. Feature File
Feature: Google Search Functionality Scenario: Search for a keyword on Google Given I open the Chrome browser When I open "https://www.google.com" And I search for "Cucumber BDD" Then I should see the results page
3. Step Definition file
package stepDefinitions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.cucumber.java.en.*; import static org.junit.Assert.*; public class GoogleSearchSteps { WebDriver driver; @Given("I open the Chrome browser") public void i_open_the_chrome_browser() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); } @When("I open {string}") public void i_open(String url) { driver.get(url); } @When("I search for {string}") public void i_search_for(String query) { WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys(query); searchBox.submit(); } @Then("I should see the results page") public void i_should_see_the_results_page() { assertTrue(driver.getTitle().toLowerCase().contains("cucumber bdd")); driver.quit(); } }
4. JUnit Test Runner
package runners; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/resources/features", glue = {"stepDefinitions"}, plugin = { "pretty", "html:target/cucumber-reports" }, monochrome = true ) public class TestRunner { }
How to Run the Tests
Right-click onTestRunner.java > Run As > JUnit Testor
Use the Maven command:
mvn test
Output
Browser opens Google
Types the query and submits
Assertion is done on the title
Generates HTML report in:
target/cucumber-reports/index.html
No comments:
Post a Comment