I am very beginner with Selenium and I'd like to get an advice how to optimize the code. I have 3 tooltips on the website and want to do the same actions for all of them.

I have written so far:

public void validateTooltipIsPresent() {

        Actions builder = new Actions(SeleniumDriver.getDriver());

        WebElement usernameTooltip = SeleniumDriver.getDriver().findElement(By.xpath("xpath1"));
        String tooltipMsg = usernameTooltip.getText();

        WebElement usernameTooltip2 = SeleniumDriver.getDriver().findElement(By.xpath("xpath2"));
        String tooltipMsg2 = usernameTooltip2.getText();

        WebElement usernameTooltip3 = SeleniumDriver.getDriver().findElement(By.xpath("xpath3"));
        String tooltipMsg3 = usernameTooltip3.getText();

My idea is to add Webelements to an ArrayList and then iterate though it. Is that good solution?

The method public void validateTooltipIsPresent() does not have any parameters, but if I add (Webelement element), then in step definitions, the arguments will be required.

This is the method in step definition:

    @Then("^In pricing section ensure tool tip display for List price, Net Price, and packaging conversion$")
    public void in_pricing_section_ensure_tool_tip_display_for_list_price_net_price_and_packaging_conversion() throws Throwable {


1 Answer 1


The problem with your code is that it's not reusable, let's consider a situation where you have a tooltip on a different page. Then you have to re-write the code again.

If you have a method like this then you can call the method multiple times instead of writing the same code again

public void validate(WebElement elem){

    WebElement usernameTooltip = elem
    String tooltipMsg = usernameTooltip.getText();


public void validateTooltipIsPresent() {

also you can parameterize cucumber

 @Then("^In pricing section ensure tool tip display for {String}$")
    public void in_pricing_section_ensure_tool_tip_display_for_list_price_net_price_and_packaging_conversion(String elemloc) throws Throwable {
      //create getter function to get the webelement using the string provided
      WebElment elem=pageobject.get(elemloc);

So that you can reuse the keywords, and reduce step length.

Note on gherkins:


THe above link gives more idea about proper gherkins. Gherkins is there to ensure functional validation and not the implementation.

So, the below step is wrong as its talking about implementation details

Given In pricing section ensure tooltip display for List price, Net Price, and packaging conversion

The functional step would be simple as:

 Given I am In pricing section
 Then tooltips are present
  • thank you So much for your help!
    – Beti
    Apr 29, 2020 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.