Home page

Showing posts with label Eclipse. Show all posts
Showing posts with label Eclipse. Show all posts

Wednesday, December 11, 2019

Selenium code for Flipkart search auto populate

Code to automate Flipkart using selenium

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 Flipkart {

    static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//drivers//chromedriver.exe"); //Chrome driver location
        driver = new ChromeDriver();
        driver.manage().window().maximize(); //Maximize window
        driver.get("https://www.flipkart.com/"); //Open Flipkart
       
        if(driver.findElement(By.xpath("//button//div//following-sibling::span[contains(text(),'Login')]")).isDisplayed()) //Checking Login button to make sure if Login popup open or not
            driver.findElement(By.xpath("(//button)[2]")).click(); // Clicking close icon of login popup
       
        driver.findElement(By.name("q")).sendKeys("iPhone 7"); //Enter iPhone 7 text in search box
        driver.findElement(By.xpath("//div[contains(@class,'col-12-12 _2tVp4j')]")).click(); //Click inside search box
       
        List<WebElement> product = driver.findElements(By.xpath("//form[contains(@class,'_1WMLwI header-form-search')]//ul//li")); //Store all Auto populated values in list object.
       
        String mobileItem = "iphone 7 plus back cover"; //Item which we want to search
       
        for(WebElement element : product) {
            if(element.getText().equals(mobileItem)){ //Compare all items with mobileItem
                element.click(); //Click matching item
                break;
            }               
        }
       
        Thread.sleep(4000);
        driver.quit();

    }
   
}


Friday, December 6, 2019

Scroll Web Page in Selenium

WebDriver driver = new ChromeDriver();

1. Scroll to specific location

- Convert driver object to Javascript executor. This is called type casting.

JavascriptExecutor JS = (JavascriptExecutor)driver;
JS.executeScript("window.scrollTo(0,2000)");

2. Scroll to specific element
- Convert driver object to Javascript executor. This is called type casting.

JavascriptExecutor JS = (JavascriptExecutor)driver;

WebElement name = driver.findElement(By.id("name")); //Store element in object of WebElement
JS.executeScript("arguments[0].scrollIntoView(true)",name); //arguments[0] means first index of page starting at 0. Pass name object so it can scroll till that element.

3. Scroll to bottom of the page
- Convert driver object to Javascript executor. This is called type casting.

JavascriptExecutor JS = (JavascriptExecutor)driver;
JS.executeScript("window.scrollTo(0,document.body.scrollHeight");

4. Scroll Horizontally
- Convert driver object to Javascript executor. This is called type casting.

JavascriptExecutor JS = (JavascriptExecutor)driver;
JS.executeScript("window.scrollTo(2000,0)");

You can use "Option 2. Scroll to Specific element" if you are aware of element.

5. Slide Bar

WebElement slideBar = driver.findElement(By.xpath("//input[@name='slidebar'"));
slideBar.sendKeys(Keys.END);


6. Scroll dynamically loading pages
- Convert driver object to Javascript executor. This is called type casting.

JavascriptExecutor JS = (JavascriptExecutor)driver;

long previousHeight = (long)(JS.executeScript("return document.body.scrollHeight"));
While(true){
    JS.executeScript("window.scrollTo(0,document.body.scrollHeight)");
    Thread.sleep(2000);
    long currentHeight = (long)(JS.executeScript("return document.body.scrollHeight"));
    if(previousHeight == currentHeight)
        break;
   
    previousHeight = currentHeight;
}

Thursday, September 12, 2019

Not getting missing package specific import suggestions in feature file for @Given / @When / @Then annotations ?

Reason: Dependency (cucumber-java & cucumber-jvm-deps) are missing in pom.xml file.

Solution:
1. Go to https://mvnrepository.com/
2. Search with cucumber-java
3. Select info.cukes » cucumber-java
4. Click latest version (1.2.5)
5. Copy 

    <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
    </dependency>
6. Paste in pom.xml
7. Search with cucumber-jvm-deps
8. Select info.cukes » cucumber-jvm-deps
9. Click latest version (1.0.5)
10. Copy  

     <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-jvm-deps</artifactId>
            <version>1.0.5</version>
            <scope>provided</scope>
    </dependency>
11. Paste in pom.xml

Tuesday, September 10, 2019

Types of exceptions in Selenium WebDriver

Types of exceptions in Selenium
  1. NoSuchElementException ---> When driver failed to locate element from DOM.
  2. NoSuchWindowException/NoSuchFrameException ---> While Switching between windows/frames failed to find mentioned window/frame
  3. NoAlertFoundException ---> Written alert Accept/Dismiss code at the wrong place
  4. TimeOutException ---> When given command failed to complete task in alloted time
  5. ElementNotVisibleException ---> Element is present in the DOM but not visible.
  6. InvalidSessionIDException ---> When session id gets expired
  7. JavaScriptException ---> When javascript executor contains incorrect JavaScript code
  8. StaleElementException ---> Once element stopped appearing in the DOM then StaleElementException.
  9. UnsupportedOperationException---> By mistake used method(deselectAll()) of Select class for single select dropdown. deselectAll() can only be used for multi-select dropdown
  10. SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75 ---> It is due to browser version and chrome driver version compatibility mismatch. If your browser is updated with latest version than check compatible chrome driver version. Replace old chrome driver with compatible one.

org.openqa.selenium.nosuchelementexception



org.openqa.selenium.NoSuchWindowException

org.openqa.selenium.NoSuchFrameException

org.openqa.selenium.noalertpresentexception

org.openqa.selenium.TimeoutException

org.openqa.selenium.elementnotvisibleexception

selenium.common.exceptions.invalidsessionidexception

org.openqa.selenium.javascriptexception

org.openqa.selenium.staleelementreferenceexception

java.lang.UnsupportedOperationException

org.openqa.selenium.SessionNotCreatedException

If you are aware of any other types of exception in Selenium then write in the comment. 

Wednesday, August 28, 2019

How to avoid mistakes in writing correct class name in TestNG.xml

It's been observed many Automation Engineer struggles in writing class name easily in TestNG.xml file and they end up spending time writing it manually. Follow below mentioned steps to get it quickly:

1. Open .java file
2. Click on class name
3. Right click on class name
4. Select "Copy Qualified Name".
5. Paste into TestNG.xml class name=""



Monday, August 26, 2019

Access Modifiers in JAVA


Access Modifier Type Accessible
Private----------------------> Within class
Protected-------------------> 1. Within class
2. Within package
3. Subclass of another package
Public-----------------------> Accessible to all classes
No Access Modifier----------> 1. Within class
2. Within package

Saturday, July 27, 2019

Generate random string

import org.apache.commons.lang3.RandomStringUtils;

public static String randomString(){
String generated_RandomString = RandomStringUtils.randomAlphabetic(5);
return(generated_RandomString);
}

Note: Save this method as a utility or in the base class and call it when random string is required to create email or anything.

Friday, July 19, 2019

Maven with cucumber

Practice URL: https://www.techlistic.com/p/selenium-practice-form.html

Editor: Eclipse


Follow below mentioned steps:


  1. Select Maven project to create new project
  2. Click Next on “Select project name and location” popup
  3. Click Next on “Select an Archetype” popup.
  4. Enter “AboutMe_techlistic_cucumber” in Group Id & Artifact Id and click Finish button.
  5. Right click project > Maven > Update Project: Check “Force Update of Snapshots/Release” checkbox and click OK button. Follow this step to avoid any conflict related to maven.
  6. Delete packages from src/main/java and src/test/java
  7. Create “Features” folder under project.
  8. Create “drivers” folder under project.
  9. Create 3 packages under src/test/java: a) pageObjects b) utilities c) stepDefinitions
  10. Right click “Fetures” folder > create new file. Give filename AboutMe.feature (Popup will open “Better editor support for '*.feature' files is available on the Marketplace.”)
  11. Install Cucumber Eclipse Plugin.
  12. Write Feature and scenario in AboutMe.feature file as follow
Feature: About Me

Scenario: Fill About Me form successfully
Given User Launch Chrome browser
When User opens URL "https://www.techlistic.com/p/selenium-practiceform.html"
And User enters Firstname as "sABC" and Lastname as "sXYZ" and Gender as "Male" and Experience as "7" and Date as "06-05-1983" and Profession as "Automation Tester" and AutomationTools as "Selenium Webdriver" and Continents as "Asia" and SeleniumCommand as "Wait Commands"
And Click on Button
And close browser



13. Create AboutMePage.java file under pageObjects package and copy paste following code:
package pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;

public class AboutMePage {
               
                public WebDriver ldriver;
               
                public AboutMePage(WebDriver rdriver){
                                ldriver = rdriver;
                                PageFactory.initElements(rdriver, this);
                }
               
               
               
                By txtFirstName = By.name("firstname");
                By txtLastName = By.name("lastname");
                By genderMale = By.id("sex-0");
                By genderFemale = By.id("sex-1");
                By experience7 = By.id("exp-6");
                By date = By.id("datepicker");
                By prefession = By.id("profession-1");
                By tool = By.id("tool-2");
                By continent = By.id("continents");
                By submit = By.id("submit");
               
                //Action methods
                public void setFirstName(String FirstName){
                                ldriver.findElement(txtFirstName).sendKeys(FirstName);
                }
               
                public void setLastName(String LastName){
                                ldriver.findElement(txtLastName).sendKeys(LastName);
                }

                public void setGender(String gender_value){
                                if(gender_value.equals("Male"))
                                                ldriver.findElement(genderMale).click();
                                else if(gender_value.equals("Female"))
                                                ldriver.findElement(genderFemale).click();
                }
               
                public void setExperience(String experience){
                                if(experience.equals("7"))
                                                ldriver.findElement(experience7).click();
                }
               
                public void setDate(String date_value){
                                ldriver.findElement(date).sendKeys(date_value);
                }
               
                public void setProfession(String profession_valule){
                                if(profession_valule.equals("Automation Tester"))
                                                ldriver.findElement(prefession).click();
                }
               
                public void setTool(String tool_value){
                                if(tool_value.equals("Selenium Webdriver"))
                                                ldriver.findElement(tool).click();
                }
               
                public void setContinet(String continet){
                                Select drpContinent = new Select(ldriver.findElement(continent));
                                drpContinent.selectByVisibleText(continet);
                }

                public void clickSubmit(){
                                ldriver.findElement(submit).click();
                }
}

14. Create steps file under “stepDefinitions” package with name “steps_AboutMe.java”.
15. Provide following dependencies in POM.xml
<dependencies>
              <dependency>
                     <groupId>junit</groupId>
                     <artifactId>junit</artifactId>
                     <version>4.12</version>
                     <scope>test</scope>
              </dependency>

              <dependency>
                     <groupId>io.cucumber</groupId>
                     <artifactId>cucumber-core</artifactId>
                     <version>4.6.0</version>
              </dependency>

              <dependency>
                     <groupId>io.cucumber</groupId>
                     <artifactId>cucumber-html</artifactId>
                     <version>0.2.7</version>
              </dependency>

              <dependency>
                     <groupId>net.sourceforge.cobertura</groupId>
                     <artifactId>cobertura</artifactId>
                     <version>2.1.1</version>
                     <scope>test</scope>
              </dependency>

              <dependency>
                     <groupId>io.cucumber</groupId>
                     <artifactId>cucumber-java</artifactId>
                     <version>4.6.0</version>
              </dependency>

              <dependency>
                     <groupId>io.cucumber</groupId>
                     <artifactId>cucumber-junit</artifactId>
                     <version>4.6.0</version>
                     <scope>test</scope>
              </dependency>

              <dependency>
                     <groupId>io.cucumber</groupId>
                     <artifactId>cucumber-jvm-deps</artifactId>
                     <version>1.0.6</version>
                     <scope>provided</scope>
              </dependency>

              <dependency>
                     <groupId>net.masterthought</groupId>
                     <artifactId>cucumber-reporting</artifactId>
                     <version>4.8.0</version>
              </dependency>

              <dependency>
                     <groupId>org.hamcrest</groupId>
                     <artifactId>hamcrest-core</artifactId>
                     <version>2.1</version>
                     <scope>test</scope>
              </dependency>

              <dependency>
                     <groupId>org.seleniumhq.selenium</groupId>
                     <artifactId>selenium-java</artifactId>
                     <version>3.141.59</version>
              </dependency>

              <dependency>
                     <groupId>com.sun</groupId>
                     <artifactId>tools</artifactId>
                     <version>1.8</version>
                     <scope>system</scope>
                     <systemPath>C:\Program Files\Java\jdk1.8.0_221\lib\tools.jar</systemPath>
              </dependency>

</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
</plugin>
</plugins>

</build>



16. Open “AboutMe.feature” file and run program by right clicking in the file > Run As > Cucumber Feature
17. Console will print all missing test steps in the form of methods. Copy all methods and paste inside steps_AboutMe.java file
18. Step 16 & 17 is for your understanding how to get ready made methods.
19. Remove content of the steps_AboutMe.java and copy paste following code:
package stepDefinitions;

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

import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion.User;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import pageObjects.AboutMePage;

public class steps_AboutMe {
  
   public WebDriver driver;
   public AboutMePage AM;
  
   @Given("User Launch Chrome browser")
   public void user_Launch_Chrome_browser() {
          System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//drivers/chromedriver.exe");
          driver = new ChromeDriver();
          AM = new AboutMePage(driver);
   }

   @When("User opens URL {string}")
   public void user_opens_URL(String url) {
       driver.get(url);
   }

   @When("User enters Firstname as {string} and Lastname as {string} and Gender as {string} and Experience as {string} and Date as {string} and Profession as {string} and AutomationTools as {string} and Continents as {string} and SeleniumCommand as {string}")
   public void user_enters_Firstname_as_and_Lastname_as_and_Gender_as_and_Experience_as_and_Date_as_and_Profession_as_and_AutomationTools_as_and_Continents_as_and_SeleniumCommand_as(String FirstName, String LastName, String gender_value, String experience, String date_value, String profession_valule, String tool_value, String continet, String string9) {
      AM.setFirstName(FirstName);
      AM.setLastName(LastName);
      AM.setGender(gender_value);
      AM.setExperience(experience);
      AM.setDate(date_value);
      AM.setProfession(profession_valule);
      AM.setTool(tool_value);
      AM.setContinet(continet);
   }

   @When("Click on Button")
   public void click_on_Button() {
          AM.clickSubmit();
   }

   @When("close browser")
   public void close_browser() {
      
   }

}

20. Create testRunner package under src/test/java
21. Create TestRun.java file under testRunner package and copy paste following code inside
package testRunner;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions
   (
   features=".//Features/AboutMe.feature",
   glue="stepDefinitions",
   dryRun=false,
   monochrome=true, //remove unnecessary characters
   plugin={"pretty", "html:test-output"}
                
                
   )
public class TestRun {

}

22. Right click inside TestRun.java file > Run As > JUnit Test.