Thursday, 3 July 2025

Complete guide and working structure Selenium with cucumber

 

Selenium professional test automation framework
✅ 1. Selenium with Cucumber

Selenium is a browser automation tool, and Cucumber is a testing framework that supports Behavior Driven Development (BDD) using Gherkin syntax. Together, they allow writing human-readable test cases (feature files) that map to Selenium code. Cucumber helps define user behavior, and Selenium automates those behaviors in browsers. This combination improves collaboration between testers, developers, and business stakeholders.


✅ 2. Selenium Web Elements

Selenium uses WebElement interface to interact with HTML elements like buttons, inputs, dropdowns, etc. Common methods include click(), sendKeys(), getText(), isDisplayed(). These elements are located using locators like id, name, xpath, cssSelector, etc. Proper element handling ensures robust and maintainable automation scripts.


✅ 3. Page Object Model (POM)

Page Object Model is a design pattern in Selenium where each webpage is represented by a Java class containing WebElements and corresponding actions/methods. It improves code reusability, readability, and maintainability. Changes in UI require updates only in the page class, not in test logic. It keeps test steps separate from locators and actions.


✅ 4. Step Definitions

Step Definitions link Cucumber feature file steps (written in Gherkin) to actual Java methods containing Selenium logic. Each step in the .feature file is implemented in a method annotated with @Given, @When, or @Then. These methods execute the actions like navigating, clicking, entering text, or asserting results.


✅ 5. Hooks in Cucumber

Hooks are special methods in Cucumber (annotated with @Before, @After) that run before or after every scenario. They are used for setup (like browser launch) and teardown (like closing browser, logging). You can also use tagged hooks to run certain hooks only for specific scenarios.


✅ 6. JUnit (with Cucumber)

JUnit is a unit testing framework for Java and is used to execute Cucumber tests. In Cucumber, the @RunWith(Cucumber.class) and @CucumberOptions annotations in a test runner class configure and run feature files. JUnit manages test execution, reports, and lifecycle management of Cucumber test cases.

✅ Example on Gmail login

✅ 1. Feature File: gmail_login.feature

Located at: src/test/resources/features/gmail_login.feature

gherkin
Feature: Gmail Login Scenario Outline: Gmail login with different usernames Given User launches "<browser>" browser and navigates to Gmail When User enters username "<username>" And clicks Next Then Gmail should prompt for password Examples: | browser | username | | chrome | your.email@gmail.com | | firefox | test.email@gmail.com |

✅ 2. Page Object: GmailLoginPage.java

java
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class GmailLoginPage { WebDriver driver; By email = By.id("identifierId"); By next = By.xpath("//span[text()='Next']/ancestor::button"); public GmailLoginPage(WebDriver driver) { this.driver = driver; } public void enterEmail(String value) { driver.findElement(email).sendKeys(value); } public void clickNext() { driver.findElement(next).click(); } public boolean isPasswordPromptPresent() { return driver.getPageSource().contains("Enter your password"); } }

✅ 3. Step Definitions: GmailLoginSteps.java

java
package stepdefinitions; import hooks.Hooks; import io.cucumber.java.en.*; import org.junit.Assert; import org.openqa.selenium.WebDriver; import pages.GmailLoginPage; public class GmailLoginSteps { WebDriver driver; GmailLoginPage page; @Given("User launches {string} browser and navigates to Gmail") public void launch_browser(String browser) { driver = Hooks.initBrowser(browser); page = new GmailLoginPage(driver); driver.get("https://accounts.google.com/signin/v2/identifier"); } @When("User enters username {string}") public void enter_username(String username) { page.enterEmail(username); } @When("clicks Next") public void click_next() { page.clickNext(); } @Then("Gmail should prompt for password") public void verify_password_prompt() { Assert.assertTrue("Password prompt not visible!", page.isPasswordPromptPresent()); } }

✅ 4. Hooks: Hooks.java (Dynamic Browser + Screenshot + Timestamp)

java
package hooks; import io.cucumber.java.After; import io.cucumber.java.Before; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Hooks { public static WebDriver driver; public static WebDriver initBrowser(String browser) { if (browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); } else if (browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", "path/to/geckodriver"); driver = new FirefoxDriver(); } driver.manage().window().maximize(); return driver; } @After public void tearDown(io.cucumber.java.Scenario scenario) { if (scenario.isFailed()) { takeScreenshot(scenario.getName()); } driver.quit(); } public void takeScreenshot(String scenarioName) { TakesScreenshot ts = (TakesScreenshot) driver; File src = ts.getScreenshotAs(OutputType.FILE); String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); String destPath = "screenshots/" + scenarioName + "_" + timestamp + ".png"; try { FileUtils.copyFile(src, new File(destPath)); } catch (IOException e) { e.printStackTrace(); } } }

✅ 5. Test Runner: TestRunner.java

java
package runner; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( features = "src/test/resources/features", glue = {"stepdefinitions", "hooks"}, plugin = {"pretty", "html:target/report.html"}, monochrome = true ) public class TestRunner { }

✅ 6. Maven pom.xml (Key Dependencies)

xml
<dependencies> <!-- Selenium --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.21.0</version> </dependency> <!-- Cucumber --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <version>7.16.1</version> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-junit</artifactId> <version>7.16.1</version> </dependency> <!-- JUnit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <!-- Screenshot Helper --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> </dependencies>

✅ Screenshots Folder (Auto-Created)

Failed scenario screenshots with timestamp will be stored in:

bash
/screenshots/ Gmail_login_with_valid_credentials_20250701_233500.png

✅ Optional: Profiles via Maven (for browser/env)

Use Maven profile in pom.xml or read from config.properties for real projects.


✅ Run the Test

  • Run TestRunner.java as a JUnit test.

  • Or from terminal:

bash
mvn test

📁 Project Structure

bash
gmail-automation/ │ ├── pom.xml ├── testng.xml (optional, if using TestNG instead of JUnit) │ ├── screenshots/ # Screenshot folder for failures (auto-created) │ ├── src/ │ ├── main/ │ │ └── resources/ │ │ └── config.properties # Optional config file (browser, base URL, etc.) │ │ └── test/ │ ├── java/ │ │ ├── hooks/ │ │ │ └── Hooks.java # Setup, teardown, screenshot with timestamp │ │ │ │ │ ├── pages/ │ │ │ └── GmailLoginPage.java # Page Object for Gmail login │ │ │ │ │ ├── runner/ │ │ │ └── TestRunner.java # Cucumber + JUnit Runner │ │ │ │ │ └── stepdefinitions/ │ │ └── GmailLoginSteps.java # Step definitions for feature steps │ │ │ └── resources/ │ ├── features/ │ │ └── gmail_login.feature # Gherkin feature file │ │ │ └── log4j.properties (optional)

Example config.properties (Optional)
properties
browser=chrome
baseUrl=https://accounts.google.com/signin/v2/identifier


✅ What Each Folder/File Is For:
PathPurpose
pom.xmlMaven config file with all dependencies
screenshots/Stores screenshots on failure with timestamp
src/test/resources/features/Contains .feature files written in Gherkin
src/test/java/stepdefinitions/Step Definitions that map to Gherkin steps
src/test/java/pages/POM classes that define UI elements and actions
src/test/java/hooks/Hooks for @Before, @After, browser, screenshots
src/test/java/runner/JUnit Cucumber test runner class
src/main/resources/config.propertiesOptional configs like browser, URL, etc.

✅ Screenshot Naming Example
screenshots/Login_with_valid_email_20250701_233701.png
✅ How to Run
bash
mvn test

Right-click on TestRunner.java → Run as JUnit Test


No comments:

Post a Comment