Home page

Showing posts with label Selenium Interview Question. Show all posts
Showing posts with label Selenium Interview Question. Show all posts

Wednesday, August 9, 2023

Selenium waits comparison

Selenium Waits Comparison

Wait Type Description Usage Advantages Disadvantages
Implicit Wait Waits for a certain time before throwing an exception if an element is not immediately available. driver.manage().timeouts().implicitlyWait(time, unit); Simplifies test code, applies globally. May cause unnecessary waiting, not precise.
Explicit Wait Waits for a specific condition to be satisfied before proceeding. WebDriverWait + ExpectedConditions Precise control, better for dynamic elements. More code, may need to handle various exceptions.
Fluent Wait Combines implicit and explicit waits, polling at specified intervals. Wait + polling + ignored exceptions Flexible, customizable wait conditions. Complex syntax, requires exception handling.
Thread.sleep() Pauses the execution for a specified amount of time. Thread.sleep(milliseconds); Simple to use. Not recommended, fixed wait time.

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();

    }
   
}


Monday, December 9, 2019

How to configure email notification in Jenkins


  1. Login to Jenkins
  2. Go to Configure System
  3. Go to bottom of the page and stop at Extended E-mail Notification section
  4. Do required setup related to credentials.
  5. Do required modification in Subject and Email template as per your requirements.

Note: Check email configuration correctly done or not from E-mail Notification section by using Test feature.

You need to enter recipients email(s) under Project Recipient section from Your Created Job > Configuration > Post-build Actions

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;
}

Friday, November 29, 2019

Jenkins Install Suggested Plugins

Following plugins Jenkins recommend to install while configuring first time:
  1. Folders
  2. Timestamper
  3. Pipeline
  4. Git
  5. PAM Authentication
  6. OWASP Markup  Formatter
  7. Workspace Cleanup
  8. GitHub Branch Source
  9. Subversion
  10. LDAP
  11. Build Timeout
  12. Ant
  13. Pipeline: GitHub Groovy Libraries
  14. SSH Slaves
  15. Email Extension
  16. Credentials Binding
  17. Gradle
  18. Pipeline: Stage View
  19. Matrix Authorization Strategy
  20. Mailer

Friday, October 18, 2019

Get count of all the links in web page

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

public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"//drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.flipkart.com/");
String newwindow = driver.getWindowHandle();
driver.switchTo().window(newwindow);
driver.findElement(By.xpath("//button[@class='_2AkmmA _29YdH8']")).click();

List<WebElement> links = driver.findElements(By.tagName("a")); //This will store all links in links object.

System.out.println(links.size()); //Use size method to get count

driver.quit();
}

}

Thursday, October 17, 2019

Difference between get and navigate methods | driver.get vs driver.navigate

Both get & navigate can be used in page loading and difference in behaviour is as follow:
  1. Wait for page to load: get will wait. navigate will not wait so navigate is faster than get.
  2. Save browser history & cookies: navigate will save so forward(), back() & refresh() commands can be used. get will not save.

Thursday, September 19, 2019

How to use CSSSelector in selenium webdriver ?

How to locate webelement using CSSSelector in selenium webdriver ?
  1. <Tag Name>#<[id='value']> for search with id
  2. <Tag Name>.<[classname='value']> for search with classname
  3. <Tag Name><[Attributename*='value']> for partial search
  4. <Tag Name><[Attributename^='value']> for start with
  5. <Tag Name><[Attributename$='value']> for ends with
  6. <Tag Name><[Attributename='value'] for exact content match of single attribute
  7. <Tag Name><[Attributename1='value'][Attributename2='value'] for exact content match of more than one attributes
  8. ParentTagName > ChildTagName[AttributeName='value'] for finding through unique parent. Use greater than sign.
  9. ParentTagName[AttributeName='value'] > TagName for finding direct child
  10. ParentTagName[AttributeName='value'] TagName for finding all direct and indirect child(Sub child)
  11. nth-child(n): Example is .classname > TagName:nth-child(1)
  12. nth-last-child(n): Example is .classname > TagName:nth-last-child(1)
  13. first-child: Example is .classname > TagName:first-child
  14. last-child: Example is .classname > TagName:last-child
  15. Sibling: Example is .classname > TagName:nth-child(1) + TagName
  16. All sibling:  Example is .classname > TagName:nth-child(1) ~ TagName
  17. Identify checked checkbox: Example is <TagName>:checked
If you have following questions then ask in comment. I'll answer on that so you can understand CSSSelector concept:
  1. What is Tag Name?
  2. What is Attributename?
  3. What is value?
  4. What is Parent Tag?
  5. What is Sibling
  6. What is Child?

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. 

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 5, 2019

Implicit wait vs Explicit wait vs Fluent wait

Implicit Wait
Webdriver will wait for given amount of time to locate the element before throwing "No Such Element Exception". If element located in less time selenium will skip remaining waiting time and start executing next step.

Syntax: driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

Explicit Wait
Webdriver will wait till condition match in given time.

Syntax:
WebDriverWait wait=new WebDriverWait(driver, 20);

Fluent wait
Webdriver will wait till condition match in given time, also it will check on regular interval as per mentioned in pollingEvery.

Syntax:
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

Tuesday, May 21, 2019

Practice XPath-1

Purpose: Get result if different parents values(answers & views) are matching based on given input.

URL: https://sqa.stackexchange.com/

//*[@title='0 answers']/../../../div[@class='views']//span[@title='7 views']

//*  selects all elements in the document
[@title='0 answers']  find title which contains value = 0 answers
/.. go to Parent
/.. go to Grand parent
/.. go to Grand grand parent
/div go to tag div
[@class='views'] find class = views
//span[@title='7 views'] go to child title = 7 views

Friday, November 30, 2018

How to solve StaleElementException

Reason behind StaleElementException: Element gets destroy and gets recreated.

  1. Refresh page
  2. Use ‘try-catch block’ within ‘for loop’
  3. Wait for the element till it gets available
  4. Using POM

Tuesday, November 27, 2018

How to solve java.lang.NoSuchMethodError:

How to solve
java.lang.NoSuchMethodError:
com.google.common.util.concurrent.SimpleTimeLimiter.create(Ljava/util/concurrent/ExecutorService;)Lcom/google/common/util/concurrent/SimpleTimeLimiter;

Steps to resolve:
1. Open POM.xml
2. Find <groupId>com.google.guava</groupId>
3. Change version of guava from 21.0 to 23.0
4. Save the file and wait for project to update the jar

Thursday, January 18, 2018

MoveToElement over javascriptexecutor

It is advisable to use MoveToElement over javascriptexecutor to track webelement and perform click event efficiently with accuracy.

Thursday, December 11, 2014

Interview Questions - 1

1. Diff between junit and testNG
- Junit required @beforecalss and @afterclass
- TestNG don't required @beforeclass and @afterclass
- In Junit testcase grouping is not possible.
- In TestNG testcase grouping is possible.

2. Diff between java 1.6 and 1.7


3. Diff between interface and abstract class

- interface is not a class.
- All variables declared in interface are final by default
- Abstract class can have non-final variables
- All the members of the interface are public by default
- Abstract class's members can be public, private etc
- To use interface it is required to use "implements"
- To use abstract class it is required to use "extends"
- A single class can implements more than one interface
- A single class can extend only one abstract class

4. Diff between final and static

- Static variable can be declared only once
- Static variable/method can be used with class name only.
- Static method can use only static variable.
- Static variable can be modified.

- Final cannot have subclass
- Sub class methods cannot override final method
- Final variable can not be modified


5. Diff between assert, verify and wait for

- If verification through assert gets failed then testcase execution will be stopped.
- If verification through verify gets failed then also it will continue testcase execution.


6. Syntax of firefox driver

- Webdriver driver - new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("http://www.google.com/");

driver.manage().window().maximize();

7. Diff between webdriver and firefox driver

- WebDriver is an interfacce
- FirefoxDriver is the implementation.


8. Disable TestNG
- @Test(enabled = false) 

9. How to perform drag and drop in webdriver:
WebElement drag = driver.findElement(By.id("drag"));
webelement drop = driver.findelement(By.id("drop"));

Action builder = new Action(driver);
Action dragndrop = builder.clickAndHold(drag).movetoelement(drop).release(drop).build();
dragndrop.perform();

1. For element which need to be drag, first create variable of WebElement for that. WebElement drag = driver.findElement(By.id("drag"));

2. For element where need to be drop, first create variable of WebElement for that. webelement drop = driver.findelement(By.id("drop"));

3. Create object of the action class for driver object.[Action builder = new Action(driver);]
4. Create dragndrop object. Action dragndrop = builder.clickAndHold(drag).movetoelement(drop).release(drop).build();
5. dragndrop.perform();


10. How to take screenshot

classname = ClickScreenShot
  1.  }catch(Exception e){  
  2.   //For failure case
  3.      File shot = ((ClickScreenShot)driver).getScreenshotAs(OutputType.FILE);  
  4.      FileUtils.copyFile(shot, new File("C:\\failure.png"));  
  5.      
  6.   }