Write Cucumber BDD Test for search functionality

  • Estimate Completion Time
    not found 30 minutes
  • Difficulty Level:

Write a feature for searching an item on an e-commerce website Flipkart. Implement step definitions to fill out the search bar and submit. Use assertions to validate the search results are displayed as entered.

Solution

Search.feature
Feature: Searching functionality on Flipkart
Scenario: Search product
 Given Flipkart is open
    When I enter a product name in the search box
    And I click on the search icon
    Then I should see the list of products related to the search

Create a new Java class to implement the step definitions and the test methods for the search feature.

CucumberEx2.java
package cucumber;
import static org.testng.Assert.assertEquals;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class CucumberEx2{

	WebDriver driver = null;

	@Given("Open Browser")
	public void open_browser() {
		driver = new ChromeDriver();
		System.out.println("Chrome Browser is open");
	}


	@When("navigate to google.com")
	public void navigate_to_google_com() {
		driver.get("https://www.google.com/");
		System.out.println("Navigate to Google");
	}

	@Then("Validate the Google page is open")
	public void validate_the_google_page_is_open() {
		String title = driver.getTitle();
		assertEquals(title, "Google");
	System.out.println("Validating the title of the webpage which is " + title);

	}

	@Then("Close the browser")
	public void close_the_browser() {
		driver.close();
		System.out.println("Closing Browser");

	}

	@Given("Flipkart is open")
	public void flipkart_is_open()
 {

		driver = new ChromeDriver();
		driver.get("https://www.flipkart.com/");

		System.out.println("Flipkart Homepage displays");
	}


	@When("I enter a product name in the search box")
	public void i_enter_a_product_name_in_the_search_box()
 {

driver.findElement(By.name("q")).sendKeys("Samsung mobiles", Keys.ESCAPE);

	}

	@When("I click on the search icon")
	public void i_click_on_the_search_button() {
		driver.findElement(By.xpath(
				"/html/body/div[1]/div/div[1]/div/div/div/div/div[1]/div/div[1]/div/div[1]/header/div[1]/div[2]/form/div/button"))
		.click();
	}

	@Then("I should see the list of products related to the search")
	public void i_should_see_the_list_of_products_related_to_the_search() {
		String actualtitle = driver.getTitle();
		String expectedtitle = "Samsung Mobiles- Buy Products Online at Best Price in India - All Categories | Flipkart.com";
		assertEquals(actualtitle, expectedtitle);

		driver.close();
	}
}
Cucumber Practice Exercises - QA Ads Banner

Proleed Academy

Proleed serves / offers professionally designed IT training courses
globally.

Copyright © 2023 - Proleed Academy | All Rights Reserved.