Is it preferred to write loops and conditions while writing my testing automation script using selenium? Is there another best practice should i use?

13 views Asked by At

I have a scenario، I want to automate it using Selenium with Java.

I have a list of products "30 Products" and I want to add specific products to the cart for example 4 products. Is it a best practice to use for loop to loop over products and add conditions to check that the current product is the same as the products to be added?**

I used for loop and conditions in my code. If there is another best practice to use?

Here is my code;

package deepDiveFunctionalTesting;

import java.util.Arrays;
import java.util.List;

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


public class AutomationTask {

    public static void main(String[] args) 
    {
        WebDriver driver = new ChromeDriver();
        
        driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
        
        int counter = 0;
        
        String [] productsNeeded = {"Brocolli","Beetroot", "Tomato"};
        
        List<WebElement> allProductsElements = driver.findElements(By.cssSelector("h4.product-name"));
        
        
        
        for(int i = 0; i < allProductsElements.size(); i++)
        {
            String productNames = allProductsElements.get(i).getText().split("-")[0].trim();
            
            List productsList = Arrays.asList(productsNeeded);
            
            if(productsList.contains(productNames))
            {
                counter++;
                
                driver.findElements(By.cssSelector(".product-action button")).get(i).click();
                
                if(counter == productsNeeded.length)
                {
                    break;
                }
                
            }
        }

    }

}

0

There are 0 answers