Where we learn technology

Tag: Selenium (Page 1 of 2)

Actions Class in selenium WebDriver for User Actions

1.Overview

In this article, we are going to explore the most fundamental phenomenon that is Actions class in selenium WebDriver.

2. Actions Class

  • We have performed single actions like sendKeys, click event till now.
  • But there are events where we need to perform multiple actions like drag and drop, right-click or pressing a key from the keyboard etc.
  • So here comes the Actions class to deal with such composite actions.
  • By selenium documentation, they have defined the Actions class as:

Actions Class
  • In simple terms, Actions class handles various types of keyword and mouse events and is available under package 
import org.openqa.selenium.interactions.Actions;
  • Syntax:
Actions actions = new Actions(driver);
  • For creating an object of an action class, you need to pass the driver object to the constructor of action class like the following :

Methods in Actions Class

Now, you can perform any composite actions as shown above with the action object. We will see a couple of examples below where composite actions are being performed.

To Note: There are two major methods in actions class are build and perform.

build() compiles all the steps into a single step and then perform() executes the step, also for single-step perform() method can be used, then there is no need to execute the build() method.

3. Mouse Hover with Actions class

  • A mouse hovers cause an event to trigger actions such as where a user places a mouse over a particular element like hovering over a tab or link. 
  • moveToElement is the method used for hovering action:

Mouse Hovering Methods

Let’s understand moveToElement(WebElement target) by code:

package com.selenium.sessions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

/**
 * 
 * @author Mandeep kaur
 * @Date May 19,2020
 */
public class ActionClass {

	@Test
	public void performsActionClass() throws InterruptedException {

		String path = System.getProperty("user.dir");
		System.setProperty("webdriver.chrome.driver", path + "/src/main/resources/chromedriver");

		System.setProperty("webdriver.chrome.silentOutput", "true");
		WebDriver driver = new ChromeDriver();

		driver.get("https://www.makemytrip.com/visa/");

		// Locate more element on the web page
		WebElement moreObj = driver.findElement(By.xpath("//li[10]/a/span[2]/span[1]"));

		Thread.sleep(1000);

		// Locate International Hotels once hovered over more element
		WebElement moveToInternationalHotels = driver.findElement(By.xpath("//li[10]/div/a[3]"));

		Actions action = new Actions(driver);

		// hover to More element then hover to International hotel and build the steps
		// in singe unit and perform the step
		action.moveToElement(moreObj).moveToElement(moveToInternationalHotels).build().perform();

		Thread.sleep(1000);
		driver.close();

	}

}

Explanation :

First, we fount out the elements where mouse hovering is required i.e more element and other is International hotels.

Then we are hovering over these elements with the moveToElement method, post that we build these steps it in a single unit using build() method and execute it with perform() method.

And we can see the above code output as:

Now, Let’s proceed with other method moveToElement(target, xOffset, yOffset);

This method is used to take the mouse on particular points on target elements.

The following is an example to deal with a slider:

Now the scenario is we need to move this slider, but how do we do that?

Let’s see the below code first to achieve this task:

package com.selenium.sessions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

/**
 * 
 * @author Mandeep kaur
 * @Date May 19,2020
 */
public class ActionClass {

	@Test
	public void moveToElementOffset_whenSuccess() throws InterruptedException {

		String path = System.getProperty("user.dir");
		System.setProperty("webdriver.chrome.driver", path + "/src/main/resources/chromedriver");

		System.setProperty("webdriver.chrome.silentOutput", "true");
		WebDriver driver = new ChromeDriver();

		driver.get("https://jqueryui.com/slider/");

		// Get the location of IFrame
		WebElement iFrame = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));

		driver.switchTo().frame(iFrame);

		// get the slider element
		WebElement slider = driver.findElement(By.xpath("//div[@id='slider']"));

		// Get the location of X,Y coordinates
		System.out.println(slider.getLocation());

		Thread.sleep(1000);

		Actions action = new Actions(driver);

		// move the element on target by X , Y coordinates
		action.moveToElement(slider, 8, 8).click().build().perform();

		Thread.sleep(1000);

		driver.close();
	}

}

Let’s break the code into the statement to get the clarity of the concept:

  1. First, we need to locate the frame, as the slider is present in the frame.

Let’s discuss little about iFrames, what are these:

  • iFrames stands for an inline frame. It is like another web page within a web page. 
  • In this case, a different document is used to embed within the current HTML document.
  • when you execute any method say findByElement for an element present in an iFrame, it will throw an exception as an element not found. 
  • For this, we first need to switch the focus to the frame to get the Element.
  • Syntax: driver.switchTo().frame();

Switching to Frame

And most importantly how we will get to know that frame is present or not, for that you need to right-click on the element and you will get View Frame Source like below

And in DOM you will get to see an iFrame tag

where <iframe> tag states an inline frame.

We can switch to the frame by index , by frame name or id or by WebElement.

2. In the above code, we have to switch the frame with WebElement.

3. Find the target element and get the location of X and Y coordinates by using getLocation().

4. Once we got the coordinates then we can slide the cursor accordingly by passing the target, x and y coordinates:

action.moveToElement(slider, 8, 8).click().build().perform(); 

 As can be seen below our slider has moved with coordinates given:

4. Drag And Drop with Actions Class

Now, there are situations where we need to perform drag and drop operation. We can also perform this scenario with the action class.

  • There is a method called dragAndDrop which drags a source element and drops on a target element.
  • We need to solve the scenario given below

Drag and Drop Image

So, here we just have to put “Drag me to my target” box to “Dropped!” box

Let’s do it by code:

Code for Drag and Drop

package com.selenium.sessions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

/**
 * 
 * @author Mandeep kaur
 * @Date May 19,2020
 */
public class ActionClass {

	@Test
	public void dragAndDropExample_whenSuccess() throws InterruptedException {

		String path = System.getProperty("user.dir");
		System.setProperty("webdriver.chrome.driver", path + "/src/main/resources/chromedriver");

		System.setProperty("webdriver.chrome.silentOutput", "true");
		WebDriver driver = new ChromeDriver();

		driver.get("https://jqueryui.com/droppable/");

		// Get the location of IFrame
		WebElement iFrame = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));

		driver.switchTo().frame(iFrame);

		// get the source element 
		WebElement source = driver.findElement(By.id("draggable"));

		// get the target element 
		WebElement target = driver.findElement(By.id("droppable"));

		Thread.sleep(1000);

		//create an object of Action class
		Actions action = new Actions(driver);
		
		// perform drag and Drop operation
		action.dragAndDrop(source, target).build().perform();

		Thread.sleep(1000);
		
		driver.close();

	}

}

So, it’s pretty clear from the above code that first it requires us to switch to the iframe as the elements are present in an iframe. Then we have to find our source and target element and just perform dragAndDrop Operation on it as has been done for you above.

And the output will be shown as follows:

 We can also have another example where certain actions need to be performed from Keyboard. User has to send some inputs from the Keyboard.

Let’s see this happening in the following example in the code:

As described in the above code, first we find the elements where keyboard actions have to be performed then with movetoElement function we move to userName element and KeyDown function to  press the shift key and sending the userName in upper case, post that KeyUp function  to  release the shift key and next we are highlighting the userName

In the end, we are clicking on signUp button with the help of Enter Key.

package com.selenium.sessions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

/**
 *
 * @author Mandeep kaur
 * @Date May 19,2020
 */
public class ActionClass {

@Test
public void keyBoardEvents_whenSuccess() {

String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.driver”, path + “/src/main/resources/chromedriver”);

System.setProperty(“webdriver.chrome.silentOutput”, “true”);
WebDriver driver = new ChromeDriver();

driver.get(“https://www.facebook.com/“);

WebElement userName = driver.findElement(By.xpath(“//*[@name=’firstname’]”));

WebElement signUp = driver.findElement(By.xpath(“//*[@name=’websubmit’]”));

// In this step, we are moving the userName element and KeyDown function press
// the shift key and sends the userName and KeyUp function perform release the
// Key and next we are highlighting the userName


Actions builder = new Actions(driver);
builder.moveToElement(userName).click().keyDown(userName, Keys.SHIFT).sendKeys(userName, “testuser”)
.keyUp(userName, Keys.SHIFT).doubleClick(userName).build().perform();

// Enter the sign up keys after we passed the userName

signUp.sendKeys(Keys.ENTER);

driver.close();
}
}

5.Conclusion

In this article, we learnt about Actions class and how we can perform various composite actions using actions classes.

Thanks for reading it! 

Cheers!!

Naveen AutomationLabs

Blog Contributors:

Author:  Mandeep Kaur

Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.

https://www.linkedin.com/in/mandeepkaur93

Reviewer: Naveen Khunteta

https://www.linkedin.com/in/naveenkhunteta

Please follow and like us:

An alternative to :nth-child

As test automation engineers, we strive to use stable and self-documenting selectors whenever possible, but sometimes using an XPath-like selector is unavoidable. The :nth-child() CSS pseudo-class, which selects an element based on its position amongst its siblings, is often used within these longer selectors. But did you know there’s an alternative to :nth-child() which is a better choice in almost every circumstance?

Element Selection

Choosing good locators is an important aspect of creating stable automated tests, reducing false-positive error rates by ensuring the correct element continues to be selected even for pages under heavy development. There are well-documented locator strategies that you can follow when crafting these locators, but even if you’re following best-practices you may find yourself in situations where an optimal locator cannot be generated:

  • Your web application uses a CSS-in-JS library: Libraries such as Styled Components and EmotionJS allow developers to define CSS styles alongside their web components instead of in separate CSS files. Defining the styling, template, and logic all inside a single JS file makes each component self-contained which helps maintainability and readability, but it comes at cost; the classes that are output by these libraries are auto-generated and lack any semantic meaning. This means that you’re going to have a bad time if you rely on these classes in your test automation. Worse yet, they have the potential to change with every new build.
  • You’re not using data attributes as stable locators: Depending on your situation, adding attributes in your application-under-test that are specifically for use by your test automation scripts may be the best way to achieve stable locators. While this offers the greatest flexibility in terms of generating locators, many teams don’t have commit-access to the application-under-test, and asking developers to do this may not be an option.
  • You want to target the ‘nth’ element in a list of elements: Even with great locators or the ability to add automation-specific data attributes, you may want to simply target a specific element among a list of elements. In cases like this it often doesn’t make sense to add a data-attribute since the attribute value may simply be an index value rather than a self-describing value like a product name or username.

In these and other situations, you’ll often find yourself using :nth-child() as part of your locator.

Using :nth-child()

:nth-child() is a CSS pseudo-class that’s supported in all major browsers and in legacy browsers including IE9. MDN defines its behavior as “match[ing] elements based on their position in a group of siblings.” In addition to its original intended use in CSS stylesheets, it’s ubiquitous in test automation scripts the world over. In fact, if you’ll often see it in selectors generated using Chrome Dev Tools’ Copy selector command.

A classic example of using :nth-child() is selecting the nth item in a list. In situations like this, you don’t want to use a locator that targets on a text value, since the item associated with that text value may change positions or may not be present at all in the future. :nth-child() is a succinct way of expressing the intention to choose not based on an element’s value, but based on its position.

But problems can arise with this approach that are not at all obvious due to how this pseudo-class works.

Drawbacks

Let’s assume you want to target the second element in the following list:

Item 1

Item 2

Item 3

The selector that you’d typically write is #list > .item:nth-child(2). If you’re using Chrome Dev Tools’ Copy selector feature to generate the selector for you, then it’s going to output the inferior #list > div:nth-child(2) selector that targets against the child’s tag name instead of class name. But let’s suppose you wanted to choose the 2nd element even if the class or tag name changes, maybe to avoid the case where a developer changes the tag name and causes your test to break. You instead use the selector #list > *:nth-child(2) which will select the 2nd element regardless of tag or class.

So far so good, but let’s consider a scenario where the page-the-under test is running ads. Often times ad platforms will generate Javascript code by dynamically inserting script tags. Using the example above, the DOM may end up in a state like this:

Item 1

Item 2

Item 3

In this situation, neither selector used above will return the expected result! #list > .item:nth-child(2) will return null because the nth child to #list is not a div! #list > *:nth-child(2) doesn’t fare much better, returning the script element.

This is a contrived example, but you would be surprised how often I’ve seen this in the wild. The automated testing tool I co-created has a feature that auto-generates selectors, and for this reason it will never generate a selector containing :nth-child, but instead uses the :nth-of-type pseudo-class.

Recommendation

:nth-of-type(), like :nth-child(), is supported by all major browsers and has subtlely different behavior in that it “matches elements of a given type, based on their position among a group of siblings”. This behavior has the distinct advantage of being closer to representing how elements actually appear within the browser. Since :nth-of-type() allows you to target on the position of a given tag, you’ll never hit a situation where a non-visible tag like script causes your tests to fail, since it ignores any elements not matching that tag in the test. In the examples above, the selector #list > .item:nth-of-type(2) matches the Item 2 element in the original example as well as the example where a script tag is the second child. This is because it ignores any elements that don’t include the item class.

In conclusion, by coupling :nth-of-type() with a stable sub-selector like .item, you get the benefit of a built-in way to target based on position (avoiding creating unnecessary data-attributes) while avoiding the potential pitfalls of :nth-child(). Consider migrating your tests over to use :nth-of-type()!

 

That’s all about :nth-of-type() in CSS Selector.

 

Cheers!!

Naveen AutomationLabs

Blog Contributors:

Author: Todd McNeal

Todd is co-founder of Reflect, a no-code test automation platform for web applications. Prior to co founding Reflect, Todd was Director of Engineering for Curalate.
 
Reviewer:
 

What is Reflect:

Reflect is automated web testing tool that anyone can use.

Automated regression tests without a line of code

Fore more details:

https://reflect.run

Please follow and like us:

Handling Browser Window PopUp in Selenium WebDriver

1. Overview

In this article, we will discuss the concept of browser window popup also the practical implementation to handle the browser window popup with selenium web driver.

2. Browser window Popup

  • Browser window popup is a window popup that suddenly pops up on after clicking on some link or on selecting an option. It just likes another web page where maximization and minimization of the web page can be done.
  • This is having its own title and url or it could be an advertisement pop up also.
  • When do we need to handle this browser window popup: if the scenario is something like: you click on some link on the main window (parent window) and some other screen pops out just another webpage (child window ), now child window demands to submit some important information and press OK once information is filled.
  • Let’s see how the browser window appears:

Browser window popup Example

3. Steps to deal with browser window popup

1. Operate on the main window that opens the popup window. For instance, click on some link on the main window.

2. Need to know the name or id of the popup window. The window Id can be fetched from Window Handler API available in selenium. it uniquely identifies the address of all the windows open at a time. Below are the methods to handle the windows:

Syntax:

driver.getWindowHandle();

  • This function allows the handling of the current window by getting the current window Handle.
  • It returns the type String.
  • On the selenium official site, this is defined as


String parentWindowObj = driver.getwindowhandle();

driver.getwindowhandles();

  • As the method name suggests windowHandles, that means there are multiple windows and to handle all these opened windows we have to use this function.
  • It returns the Set of String.
    • Set<String> handles = driver.getwindowhandles();
  • Set stores the unique values and handle of all the windows that will be unique.
  • Below description clearly says the same:
  • Set values are not stored based on the index, so to iterate over the set, we need to use the Iterator to get the handler values and this method will give you an iterator of string.
  • This Iterator will be available in java. util package.
Iterator<String> it = handler.iterator();

//get the window ID for Parent a& Child now
String parentWindowID = it.next();
String childWindowID = it.next();

3. switch the driver to the popup window

driver.switchTo.window(childWindowID);

4. Perform some actions in the popup window such as get the title or close the button/tab etc.

driver.switchTo().window(childWindowID);
String title = driver.getTitle();
System.out.println("child window title is : " + title);

//close the pop up window now by using driver.close() method.
driver.close();

tip: Make sure, you are using close() to close the pop up. If you use quit() it will close parent and child both.
This is the basic difference between close() & quit().

5. Switch back to the parent window by passing the parentWindowID.

driver.switchTo().window(parentWindowID);
String title = driver.getTitle();
System.out.println("parent window title is : " + title);

//close the parent window by using quit:
driver.quit();

Let’s see the below code for a complete understanding of the concept:

Full code to handle Browser window popup:
package SeleniumSessions;

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class BrowserWindowPopUp {

public static void main(String[] args) {

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

driver.get(“http://www.popuptest.com/goodpopups.html”);

driver.findElement(By.linkText(“Good PopUp #3”)).click();

Set<String> handles = driver.getWindowHandles();

Iterator<String> it = handles.iterator();

String parentWindowID = it.next();
System.out.println(“parent window id is : ” + parentWindowID);

String childWindowID = it.next();
System.out.println(“child pop up window id is : ” + childWindowID);

driver.switchTo().window(childWindowID);

System.out.println(“child window title is ” + driver.getTitle());

driver.close();

driver.switchTo().window(parentWindowID);
System.out.println(“parent window title is ” + driver.getTitle());

}

}

Important Tip:

One thing to notice here is that we have to come back to parent window if any further actions have to performed on Parent window. Without switching to parent window will not allow us to perform any action on parent window page.

Let’s add another example to get more understanding of the concept:

Suppose four windows are open and we want to switch to the third window.  

  • First Approach: using Set and iterator we have already seen above.
  • Second Approach: Using ArrayList. The benefit of this approach is you can easily deal with any window. The parent window will start with an index 0.

Let’s see the code with ArrayList:

package SeleniumSessions;

import java.util.ArrayList;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserWindowHandleList {

public static void main(String[] args) {

System.setProperty(“webdriver.chrome.driver”, “/Users/NaveenKhunteta/Downloads/chromedriver”);

WebDriver driver = new ChromeDriver();

driver.get(“http://www.popuptest.com/goodpopups.html”);

driver.findElement(By.linkText(“Good PopUp #3”)).click();

Set<String> handles = driver.getWindowHandles();

ArrayList<String> ar = new ArrayList<String>(handles);

System.out.println(ar);

String parentWindowID = ar.get(0);

System.out.println(parentWindowID);

String childWindowID = ar.get(1);

System.out.println(childWindowID);

driver.switchTo().window(childWindowID);

System.out.println(“child window title is “ + driver.getTitle());

driver.close();

driver.switchTo().window(parentWindowID);

System.out.println(“parent window title is “ + driver.getTitle());

}

}

 

And we’ll get the output as following:

As can be seen through the above code, you can easily browse through the windows following this approach.

6. Conclusion

We have learnt to handle  browser window popup using windowhandler API in Selenium WebDriver. We have solved this use cases by using Set and List both.

That’s about it.



Cheers!!

Naveen AutomationLabs

Blog Contributors:

Author:  Mandeep Kaur

Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

Please follow and like us:

JS Alert Popup, Auth Pop Up and File Upload Pop Up Handling in Selenium WebDriver

1.Introduction

In this article, we’re going to illustrate how to handle alert or javascript Popup using selenium WebDriver.

2. Basics

Let’s get started by understanding what are these alerts or javascript popups.

  • Javascript Alert/popup is a notification/warning or message displayed on the User interface in box format to notify the user about some information or asks for permission to perform certain kind of operations.
  • Alert is a method in javascript and  displays an alert box with a specified message and an OK button.
  • what do we need to generate this alert on UI is simply open inspect window and click on console and type alert(“Hi this is an automation User!!”) . 
  • you will be able to see the popup similar to this:

3. Types of Alerts

  1. Simple Alert
  2. Confirmation Alert
  3. Prompt Alert

Let’s have a look at the first one:

Simple Alert:

This alert is called simple alert because it just notifies the user some information or warning with an “OK” or “Close” button as shown in the following image.

  • The above popup can not be handled with finding XPath of OK Button as we can not inspect or spy over this button.
  • So, to handle the above Popup, we need to look at Alert interface of selenium WebDriver

Alert Interface

  • Alert is an interface in selenium provide some methods to handle the alert
  • Syntax:
  • Alert alert= driver.switchTo().alert();
  • To handle the Alert, we first need to switch to alert using switchTo() method.
  • WebDriver interface contains method switchTo() which has return as interface and contains method alert() which has return type as Alert interface. 
  • RemoteAlert class in RemoteWebDriver class implement this Alert Interface
  • For complete code reference, visit over
  • RemoteWebDriver Implementation
  • alert() switches to the alert and return an alert reference and throw “NoAlertPresentException” if no alert exists.
  • Next, Let’s what actions we can perform once we switched to an alert

1.void dismiss(): This method clicks on the ‘Cancel’ button of the alert or dismiss the popup . It returns void.

Syntax:

driver.switchTo().alert().dismiss();

2.void accept(): This method click on the ‘OK’ button of the alert and returns void

Syntax:

driver.switchTo().alert().accept();

3.String getText() : This method captures the alert message and returns the String.

Syntax:

driver.switchTo().alert().getText();

4.void sendKeys(String Text):This method passes some data to alert input text and it returns void 

Syntax:

driver.switchTo().alert().sendKeys(“Text”);

Back to simple alert , let’s see following snippet code

 

Simple Alert

As can be seen, for simple Alert we just need to click on OK button and with one statement by switching to alert and accepting it we can achieve this scenario.

  • Confirmation Alert

  • Confirmation Alert is the alert which asks for confirmation from the user to perform certain actions.
  • User can opt for OK or Cancel button based on the requirements and also we can not inspect over this alert also.
  • Let’s see how it looks like

Following code snippet for the same:

package com.example.automation;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author Mandeep Kaur
 * @Date 6 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) throws InterruptedException {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://testuserautomation.github.io/Alerts/");
        driver.findElement(By.xpath("//button[2]")).click();

       Alert alert = driver.switchTo().alert();
       System.out.println(alert.getText());
        //For OK button in alert, accept the PopUp
        alert.accept();
        Thread.sleep(2000);
        WebElement text =driver.findElement(By.xpath("//*[@id='demo']"));
        //verify the text after accepting the popUp
        System.out.println(text.getText());
        driver.close();

    }
}

As shown in the code, we have accepted the alert and verify the text we got after running the above piece of code and we get output similar to:

  • Prompt Alert

  • This Alert is to get input from the user in the form of text.
  • From the above methods, we have to use alert.sendKeys() method to send the text in an alert
  • After entering the input, the user can press the OK or Cancel Button.
  • Let’s prompt Alert on UI

 

prompt Alert

Now , see the code snippet for the same:

package com.example.automation;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


/**
 * @author Mandeep Kaur
 * @Date 6 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) throws InterruptedException {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://testuserautomation.github.io/Alerts/");
        driver.findElement(By.xpath("//button[3]")).click();

       Alert alert = driver.switchTo().alert();
       System.out.println(alert.getText());
       //Send Text to the Alert
        alert.sendKeys("TestAutomationUser!!");
        //For OK button in alert, accept the PopUp
        alert.accept();
        Thread.sleep(2000);
        WebElement text =driver.findElement(By.xpath("//*[@id='test']"));
        //verify the text after accepting the popUp
        System.out.println(text.getText());
        driver.close();

    }
}

We can see that here before accepting the Popup, we have sent the “TestAutomationUser” to the alert and verified the text after we accepted the popup and output will be like following

 
 
 
Do we have some other pop ups as well? 
Answer is YESSS…
 
 
Now, there are few other Popups such as Authentication popup and window-based  popup like file Upload , we need to have strong understanding to tackle such popups :
Let’s quickly discuss about Basic Authentication Popup First: 
 
1) Basic Authentication popup : It asks user to enter username and password to the popup  when the browser gets launched and it looks like something :
As can be comprehended from the above snapshot that we need to pass username and password and we can’t spy over this popup.
Let’s look at below code snippet to handle this popup

 

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

/**
* @author Mandeep Kaur
* @Date 6 May,2020
*/
public class SeleniumConfig {
public static void main(String[] args) throws InterruptedException {
String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);
WebDriver driver = new ChromeDriver();

//send username : admin and password: admin in url before launching the browser
driver.get(“https://admin:admin@the-internet.herokuapp.com/basic_auth”);

//validate if popup is closed successfully and capture the text

WebElement successMessage = driver.findElement(By.xpath(“//div[@class=’example’]//p”));

System.out.println(successMessage.getText());

}
}

It’s pretty clear from the above code that we just need to pass the username and password in the URL and after “@” the complete URL, after that, we can verify the success message, this is how we can achieve our goal.

2) Window-based File Upload popup :

Window-based popup interacts with window operations, selenium doesn’t provide direct support to handle this type of popup  but there is a workaround to operate on such cases. let’s look down to understand this in detail:

Window/ Mac-based popup appears like this once you click on choose file:

Let’s see the code to handle this popup:

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

/**
* @author Mandeep Kaur
* @Date 6 May,2020
*/
public class SeleniumConfig {
public static void main(String[] args) throws InterruptedException {
String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);
WebDriver driver = new ChromeDriver();

//launch the url
driver.get(“https://the-internet.herokuapp.com/upload”);

//inspect over the choose file element and send File from your directory to it
WebElement uploadFile = driver.findElement(By.xpath(“//input[@name=’file’]”));
uploadFile.sendKeys(“/Users/Documents/index.html”);

//click on upload button
driver.findElement(By.xpath(” //input[@class=’button’]”)).click();

//verify the message
WebElement successMessage= driver.findElement(By.xpath(“//div[@class=’example’]//h3”));
System.out.println(successMessage.getText());

driver.close();
}
}

Explanation:

1. We first need to inspect over choose file Button and capture XPath, HTML to look like below where it should have <input> tag and type should be file:

<input id=”file-upload” type=”file” name=”file” xpath=”1″>

 

2. Next, need to send File to upload using sendKeys(String fileNameWithExtension);

3. It will upload the file and we can verify the file is uploaded or not by capturing the success message like following:

4. Conclusion

In this write-up, we have learnt about javascript alerts, a few other types of popups and various ways to handle all these popups.

 

That’s all for this post, hope you have learnt about PopUps 🙂

 

Cheers!!

Naveen AutomationLabs

 

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

 

Please follow and like us:

Image Resolution Issue in HeadLess Mode

If you have seen this strange issue while running the test in HeadLess mode. You might be getting lower resolution of the images or thumbnail png’s from the site.

Please use below code:

ChromeOptions options= new ChromeOptions();
options.addArguments(“window-size=1400,800”);
options.addArguments(“headless”);
WebDriver driver =  new ChromeDriver(options);

You can also use Dimension class from Selenium:

Dimension dim = new Dimension(width,height)
driver.manage().window().setSize(dim)

Server is checking the headless browser as not needing the higher resolution of the images. This solution will help you to set the widnow-size to “1400,800”. You can try this and take the screenshot of the page. in Headless. You should get higher resolution and clear images.

This is just a small trick 🙂


Cheers!!

Naveen AutomationLabs

Please follow and like us:

Difference between ImplicitlyWait, ExplicitWait and FluentWait in Selenium WebDriver

1.Overview

In this article, we’ll look at the most fundamental mechanism in selenium – synchronisation(wait).

2. Synchronisation in Selenium

  • Synchronisation helps the user to troubleshoot issues when launching or navigating to different web pages while executing the selenium scripts.
  • When the entire web page gets refreshed or elements are getting re-loaded there should be synchronisation between the selenium scripts, script execution speed and web application speed.
  • At times, there can be a lot of Ajax components or some images and when we want to interact with these elements it may not visible. Thus, a time fall back can be seen in such cases and we get an exception as “ElementNotVisibleException“.
  • Selenium doesn’t provide any default synchronisation but it provides synchronisation in the form of different types of waits which we will see below.

3. Different Types of waits in Selenium WebDriver

  • Implicit Wait
  • Explicit Wait
  • Fluent Wait

These waits are dynamic waits. To understand the statement let’s consider a situation when you have given a TimeOut value of 20 seconds. If the element is loaded in 5 seconds, then rest 15 seconds will be ignored.

Let’s have a look at each one of these commands:

  1. Implicit Wait

As per Selenium Documentation, An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

  • Implicit wait waits for a certain time till page gets loaded. After setting a particular time web driver will wait for that time before throwing an exception “No Such Element Exception“.
  • Implicitly wait is applied globally, which means it is always available for all the web elements throughout the driver instance.
  • Syntax: driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  • Implicitly accepts two parameters the first parameter time: 10 given as timeout wait and other is TimeUnit can be given in seconds, minutes, hours days just put dot key after TimeUnit, we can see all the options available.

Implicit Wait
 

So do I need to use Implicitly Wait? Answer is really NO..

Dis-advantages of Implicitly Wait:

  • undocumented and practically undefined behaviour.
  • runs in the remote part of selenium (the part controlling the browser).
  • only works on find element(s) methods.
  • returns either element found or (after timeout) not found.
  • if checking for absence of element must always wait until timeout.
  • cannot be customised other than global timeout.

This list is gathered from observations and reading bug reports and cursory reading of selenium source code.

Let me tell you one thing : <Always use explicit wait. Forget that implicit wait exists>                                              --Naveen Khunteta

2. Explicit Wait

Explicit wait is of two types:

a) WebDriverWait (Class) : 

b) FluentWait (Class)

Both are classes and implements Wait interface.

WebDriverWait class is an extension of FluentWait class. It doesn’t have its own methods.

  • Explicit wait waits for a certain condition till specific element is not loaded.
  • Its implementation is given by WebDriverWait Class in selenium with some expected conditions.
  • This can be useful when certain elements on the webpage are not available immediately and need some time to load for e.g when you click on some submit button after you fill some registration form, then it takes some time in processing and displaying the data on UI.
  • Selenium has its predefined conditions provided in ExpectedConditions class.
  • Below is the syntax to define explicit wait and the expected conditions to be selected based on our needs:

Expected Conditions

So do I need to use Explicit Wait? Answer is YESSSS..

  • documented and defined behaviour.
  • runs in the local part of selenium (in the language of your code).
  • works on any condition you can think of.
  • returns either success or timeout error.
  • can define absence of element as success condition.
  • can customise delay between retries and exceptions to ignore.

Fluent Wait:

As per Official Selenium API Documentation, FluentWait is:

An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.

Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

  • FluentWait is used when we can define the maximum time to wait for a condition, It also defines the frequency with which WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
  • We can configure the wait to ignore specific types of exceptions while waiting, such as NoSuchElementException when searching for an element on the page.
  • The fluent wait is a class and an implementation of Wait interface and also parent class of WebDriverWait.
  • We can customise the below apply method to give any conditions based on our specifications.

Syntax:

Let’s below code snippet :

Code for Fluent Wait

package com.example.automation;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
import java.time.Duration;
import java.util.function.Function;

/**
 * @author Mandeep Kaur
 * @Date 2 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        // Create object of WebDriverWait class

        Wait wait = new FluentWait(driver)
                //Wait for the condition
                .withTimeout(Duration.ofSeconds(10))
                //checking for its presenceonce every 5 seconds.
                .pollingEvery(Duration.ofSeconds(5))
                //Which will ignore the Exception
                .ignoring(Exception.class);

        WebElement element = wait.until(new Function<WebDriver, WebElement>() {
            @Override
            public WebElement apply(WebDriver driver) {
                return driver.findElement(By.name("lastname"));

            }
        });
        element.sendKeys("Martin");
    }
}

Explanation:

To put it simply, Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.

  • The above code defines time out value as 10 seconds and polling frequency as 5 seconds that means for every 5 seconds it keeps on checking for element.
  • It directs WebDriver to wait for a maximum of 10 seconds to verify a specific condition. If the condition occurs during those 10 seconds, it will perform the next step in the test script. If not, it will throw an “ElementNotVisibleException”.

So when should I use FluentWait?

  • When you do not see suitable expected wait condition in explicit wait.
  • To handle dynamic AJAX web elements with polling mechansim
  • You need to do more than just waiting along with Polling Mechanism, IgnoredException and when you want to create your own custom wait condition (in apply method) for non WebDriver use cases as well.
So can I use FluentWait features like, polling interval, ignoreAll with WebDriverWait? 
Ans
: Yes, of course you can do that, as I have explained earlier WebDriverWait is child class of FluentWait, so it has access on all parent class public methods.

Refer this WebDriver API on GIT:

https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/support/ui/FluentWait.java

Final Conclusion:

a. Wait is an Interface in Selenium and having only one method declaration:

public interface Wait {

until(Function<? super F, T> isTrue);

}

b. FluentWait is a class which is implementing Wait Interface, it’s having its own methods shown above and overridden until() method from the wait Interface. 

public class FluentWait implements Wait<T> { }

c. WebDriverWait is extending FluentWait class but has no methods init except one overridden method, that is: timeoutException(){}.

WebDriverWait can use all the methods of FluentWait class – pollingEvery(), withMessage(), ignoreAll etc..

FluentWait can be used for both WebDriver and non WebDriver use cases. It just needs a condition – waitForCondition.

3. Concept of Thread.sleep()

  • It is a static wait and execution of the scripts will be on hold till specified time configured in the function.
  • Thread is a class in JAVA and sleep is static method.
  • sleep() methods accept duration in milliseconds. ( 1 s= 1000 ms).
  • It throws  IllegalArgumentException – if the value of ms is negative.
  • sleep() throws a checked exception which we must either throw or handle it using try catch like done below
  • Syntax:

try{
Thread.sleep(5000);
}
catch(InterruptedException e){
}

Note: it’s never a good idea to use thread.sleep () as unlike dynamic waits it will wait for the entire time configured in the function till the element gets loaded.

4. PageLoadTimeOut & SetScriptTimeOut property

PageLoadTimeOut

  • PageLoadTimeOut is focused on the time a webpage needs to be loaded – the page load timeout limits the time that the script allows for a web page to be displayed.
  • If the page loads within the time, then the script continues. If the page does not load within the timeout the script will be stopped by a TimeoutException.
  • The timeout is set at the driver level. After creating the driver instance with the appropriate driver capabilities.
  • Syntax :

   driver.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);

SetScriptTimeOut

  • From WebDriver documentation: setScriptTimeout(long time, java.util.concurrent.TimeUnit unit) sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.
  • This works only for Async scripts (executeAsyncScript: calls which takes some time to respond back)
  • Syntax:

driver.manage().timeouts().setScriptTimeout(1, TimeUnit.SECONDS);

5. Conclusion:

In this article , we learnt about the various waits in selenium WebDriver.

Some References taken from:

 
Blog Contributors:
Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta
Please follow and like us:

Real Time Interview Questions – Selenium/API/Mobile/UIAutomation

This is the list of all different interview questions, which were asked in different companies located worldwide. 

I have collected these questions from different people who have recently experienced and attended various interviews in different companies. 

I am sure these questions will help you to prepare more on the basis of real time interview questions.

You can also get an idea in which company these questions were asked, so that you can prepare accordingly. 

If you want to add more questions to this list, please feel free to fill this form:

 

Which Category?
What are your questions?
In which company, these questions were asked? 
City, Country
What did you answer for this question? (Not Mandatory but, would like to know what exactly you answered)
Did  you clear that round?
Selenium, API/BackEnd 1. what’s selenium? Google, India Bangalore, india NA Yes
Selenium Challenges faced in Selenium Automation and how did you handle that error? Capgemini, USA Manchester, New Hampshire, USA   No
Selenium What do you mean by ROI? Cognizant Kolkata, India   No
Selenium How we can restrict object creation of class, diff between default and protected, SQL queries where 3 tables were gave book, publisher and library like that, design patterns used in project ex single time design pattern etc Ziametrics, Pune Pune Default is PKG level and protected can be used in sub class of diff PKG as well.we can restrict object creation by making constructor private,  No
Appium, Jenkins, Maven, TestNG, Cucumber How to Automate Ionic Hybrid apps and what all challenges have you faced while Automation?

How to handle synchronisation issues in Appium?

What alll challenges have you faced in Appium setup with Emulator?

How Jenkins Build Management flow is done?

How to Develop a Framework for Automation ? What all basics things you will be doing

Structure of framework is asked 
KPISOFT PVT LTD Bengaluru   Yes
Selenium, API/BackEnd, Appium, Performance Testing, Jenkins, Maven, WebDriverIO, TestNG, Cucumber Selenium Cognizant Bangalore, india   No
Not Listed here How costumer involved in our project?  MFX Solutions Bengalore, India   Maybe
Selenium, TestNG Different types of annotations in TestNg;xpath differences, Difference between float and double variables;Hash Maps related questions to count the repetition of characters;Date class in java;program to convert one date format to other form Wellsfargo; Hyderabad Hyderabad,India   Yes
Selenium, API/BackEnd, Rest Assured, JMeter What is Remote Webdriver?
Use of Interface in YourCurrent Automation Framework?
How can we upload file in headless browser mode if field is not file type(without using sendkeys)
Desired Capabilities Vs Chrome Options?
Crestech,Noida New Delhi,India Answered all except Upload File one. Maybe
Selenium How to reverse an Integer? Oracle, Chennai Chennai   No
Selenium When you navigate the application url there is one cookies accept popup. It will not come again if you accept it once. You write one method where you accept it then other test method dont need to accept it. Then if  clint dont want to test that method and if you run without run that test method you got error as you need to accpt pop up before proceed further. Civica vadodara Ahmedabad Give a if else condition if it displayed then click on accept.

But it gone wrong when I checked at home as if elements itself not there then its throws no such elements exception
No
Selenium Where do you have your jar files?
Difference between Hash table and hashmap?
Where you have used hash map in your project ?



Gogo -Chennai Chennai , India    No
Selenium, TestNG, Cucumber Let say we have 10 number and one button. I want to delete those numbers but should delete alternatively – what should be the best ways to delete by clicking on the button.

For eg: if i click on button then alternate number should be deleted.
Eclinicalworks- mid scale Mumbai I was not aware about this No
Selenium What is the best CSS or Xpath ?Why? What are Browser engines?
Why do we need them?
CA Tanuku I have answered CSS..Unable to provide proper resolution for my answer..Please help No
Selenium, TestNG 1. Difference between Remote webdriver and webdriver.
2. Difference between plugins and dependencies.
3. What is thread count in testng.
Harbinger Pune   No
Selenium  write xpath or css anything for check availability button on IRCTC page for travel from Howrah to new Delhi on Poorva express.

I wrote (//button[@id=’check-availability’])[3] (as  Poorva express was showing on 3rd number), but the interviewer said that poorva express can be on any number. So write a general expression.
Publicis sapient, Skype interview for bangalore location Kolkata   No
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber I thought I had the answer. Still, I wanted to be sure, so I asked a key employee. Systems Limited Karachi, Pakistan While this is probably the most commonly asked interview question, so many people either fail to prepare for it or have no idea how to approach it. What most people end up doing is giving a summary of their resume and/or personal history, which is exactly what you should NOT do. No
Selenium Drag and drop between two frames,The drag part is in one frame and drop part is in another frame and then when have to use drag and drop Wipro, Noida Kolkata   No
Selenium While running a script, you are getting “NoSuchElementException”. But you have taken the correct locator(ID, XPATh or CSS). Still you are facing the same issue. What might be the reason? Cognizant Bhubaneswar, India I answered like this. I said that particular web element may be present in a frame. So if you are not switching to that frame before doing any action on that web element then you will get “NoSuchElementException” even if you have taken the correct locator.  Yes
Selenium, API/BackEnd, Appium, Postman, JMeter, Jenkins, WebDriverIO, TestNG jjnjnjn jaffna Jaffna njnkninkiniknkn Yes
Selenium, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber How to read Excel data through hash map? Chennai- CTS Chennai Yes Maybe
Selenium, API/BackEnd, Appium, Rest Assured, Postman, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber Looking questions on above topics ABC Noida,India   Maybe
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber How to write api response in excel file and compare these response with newer response? Simform _ Ahmadabad. Baroda I was not aware about that concept. But I have gave answer to him we can compare string with json response. Yes
Selenium, API/BackEnd, Rest Assured, JMeter Java coding series need more questions on Java . Soap webservices automation .How to write program to read data from Excel sheet using apache poi. Most of companies asked these thing in Selenium interview also gave selenium scenario can u Plz add those also Pondicherry,India   No
Selenium 1) How to take the full page screenshot? TakesScreenShot will not take the full page screenshot.
2) How to record the video for your test case execution.
3) What are the five interfaces we use in Selenium.
4) How to achieve parallel execution using TestNG.
5) We use different cucumber options like glue, dry run…where these keywords are defined and what is the internal working of them. 
Sunlife Gurgaon Noida   No
Selenium Where u have used overriding and overloading concepts in ur project.

Ur inputs in designing the framework

How to avoid stale element exceptions

Different exceptions u get

Testng parametrization


Altran, gurgaon  New delhi  Gave the wrong answer  No
API/BackEnd How did you automated kafa stream based services .. what is Kafka.. . Have you done Kafka testing bangalore   Yes
API/BackEnd, Rest Assured – How to prepare test data in automation for APIs to be tested? What utilities like TestNG/ Data provider we can use?
– As per you, what is the most important aspect/points in writing API automation ? Writing unit/integration seems happy flows and APIs are intent to work accordingly. But what are the other important aspect we should care about? 
– I find it very difficult in writing CORE framework classes(logic) using programming paradigm though my programming concepts are clear. How I can overcome from this?
– 
These Q are driven by me and comes in a mind whenever we work on automation INDIA   Maybe
Selenium, Maven, TestNG Difference Between Maven and Java Project ?
Why syntax is “driver.manage().window().maximize()?Why are we using dot?
TDD over BDD why?
Difference between Pagefactory and POM ?
Deloitte – Telephonic  Pune Ans 1.Told that  We maintained Project Structure using maven , add dependencies , and other Jars .
Ans 2.  Told we are using in interface and inheritence ,but wasn’t able to explain properly.
Ans 3. Couldn’t ans at that Time.
Ans 4. Page factory used for initialization of webelements and POm is design Pattern 
No
API/BackEnd Find the next immediate bigger number using the same digits.
Finding the maximum occuring element in an array.
Matrix multiplication
merge sort
Juniper networks Bangalore   Yes
Selenium Related Captcha automation  Deloitte, Bangalore Kolkata,India   Maybe
Selenium In the home page of the money control website, there is a horizontal banner where data keeps moving in the horizontally. How to validate using selenium whether data is moving or not? Pwc Hyderabad   No
Selenium How can u find xpath of two elements with same id, name, class. Accenture Delhi   No
Selenium 1). Why are you managing Locators and method in SinglePage.java?Why don’t you manage entire locators in any other LocatorsPage.java(Something type).

2). How to get color of text in selenium?
Capegmini,Bangalore 2). Oracle Bangalore BANGALORE The reply I told them it will  easy to manage all locators and method in single page.So, sometimes what happen by mistake tester change some other locator which is very confusing for tester and they have debug the testcases.

2). driver.findElement(By.id(“id_name”)).getCssValue(“color”);
No
Not Listed here When you develop and deploy an application, user is not able to access it, What do you check first? How do you find a solution?

What initiative did you take to improve the product or organization in your previous company?
Company: Visit Scotland, Edinburgh, UK Edinburgh,United Kingdom   No
Selenium, API/BackEnd, Rest Assured, JMeter, GIT/Bitbucket, TestNG 1. TestNG xml file format(suite name, test name)
2.  Selenium – How to read value from excel sheet
3.  Java – conditions of if .eg output of if(0)
4.  Java8 – Bigdecimal – How to add two bigintegers
5.  Git – How to get master branch into current branch(command)
6.  Selenium – How to check all links on a page
7.  Selenium –  Retry Logic for failed test cases
8.  API – @Autowired,@Getter,@Setter .
9.  API – How to write single test case with multiple testdata(answer – @ParameterizedTest)
10. Top Down and Bottom Up Approach
11. How to handle captcha through selenium
12. JMeter – Ramp up, Through put in detail
13. Selenium – Framework in detail
14. API – Status Code, 500 and 400
Nokia – Gurgaon, Fidelity – Gurgaon, Emirates – Dubai Dubai,UAE   Maybe
Selenium Diff types of wait and explain why? 2. Explain framework which u used in ur project?  TCS USA Allentown USA   Yes
Appium Appium architecture ,Configuration,IOS configuration ,How to scroll using x, y coordinate. Bangalore Bangalore,India   Yes
Selenium While running a script, you are getting “NoSuchElementException”. But you have taken the correct locator(ID, XPATh or CSS). Still you are facing the same issue. What might be the reason? Cognizant Bhubaneswar, India I answered like this. I said that particular web element may be present in a frame. So if you are not switching to that frame before doing any action on that web element then you will get “NoSuchElementException” even if you have taken the correct locator.  Yes
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber Api rest assured framework setup Xebia Gurgaon   No
Selenium How to make Webdriver Threadsafe? Cognizant, Gurgaon Noida,India I was not able to answer this, infact only this question. No
Selenium, API/BackEnd, Appium, Rest Assured, Postman, Jenkins, Maven, TestNG, Cucumber API , Cucumber Most Of the Companies India   Yes
Selenium, API/BackEnd 1. How to add new functionality to production without altering the source code of existing prod code?
2. Take screenshot of data streaming in application(capture for every mili sec and save it in single file)
3. Create framework for coffee vending machine?
4. Write xpath for dynamic table which having no unique locators & text inside every column is dynamic.
5. Write a program to enter any product and find suggestions (products and count of them)available below page.
6. Class abc having set of 10 methods which will executed 10 times using loop. I want 5th method to be executed only thrice. How to achieve this without using if/else conditions.
(question#- company)  1.2 – Cenduit, 3- Empower Retirement, 4- HCL, 5,6 – IBM . Lacation is Bangalore. Bangalore, India 1. Create new service and integrate it to prod code.
2. Using java script method – capture stream
3. Created methods to check availability of productions like milk coffe water etc, type of coffee selection, serve coffee , keep track of no. Of coffees served, total capacity of vending machine, trigger signal when coffee gets over.Integrated all these in single class.
4. Take the position of row and column
5.Using product api can check suggestions are relevant to product and count of them
No
Selenium, API/BackEnd, Appium, Rest Assured, Postman, Jenkins, WebDriverIO, TestNG 1. Justify that webdriver is an interface
2. Why webdriver is implemented as an interface not abstract class
3. How can we make object repository in such a way so that if UI object properties are changed even then our objects do not fail-Note we do not have to use traditional locators.
4. Can you do performance testing using selenium webdriver
5. Write a JAVA PROGRAM which will implement postfix notation algo
6. Write a program which can print the alphanumeric string in the sequence such that first only digits gets printed and then characters in descending order
7. Write a java program which will print number of words in a string having repeated characters. Print the characters with count.
Kronos – Noida, Thoughtworks-Bangalore, Sapient-Gurgaon Bangalore, India n/a Yes
Selenium, API/BackEnd, Jenkins, Maven, TestNG Exceptions in webdriver Capegemini Hyderabad   No
Selenium, API/BackEnd, Rest Assured How do you handle dynamic json response in API Automation?
How to handle multiple cookies in rest assured?
Pico container in cucumber
FIS, HCL Chennai, India    No
Selenium How to handle the conflicts in GIT Increwin Technologies,banglore Pune, India   Yes
Selenium, API/BackEnd, Rest Assured, Postman, JMeter, Performance Testing, Maven, GIT/Bitbucket, TestNG, Cucumber Not attend automation interview Jaipur Jaipur   Maybe
Selenium Difference between WebDriverWait and FluentWait? Amazon Bangalore   Yes
Selenium Oops concept, HashMap specifically in collections, waits. GeP, Mumbai and L&T, Mumbai India Explained HashMap’s storage and retrieval process. Explained 3 waits and same for Oops Yes
Selenium Where did you use method overloading and overriding in your project?  Accenture, Gurgaon  Noida, India   Maybe
Rest Assured Rest assured , how you verified backend data . If application change always.  NC Newyork    Yes
Selenium, API/BackEnd, Rest Assured, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber wap to define a set of 5 integers in a single line of code
In Cucumber, how do you execute parallel testing
Selenium Architecture
Exceptions in method overloading
How to log event in selenium without using testng

Commons one
Java 8 features
Xpath and its type
Waits and Timeouts
Pune Pune   Yes
Selenium Selenium Automation Testing Real world Interview Question and Answer

 

Question: – How to switch from frame to main window? With syntax.

Answer: – We can give frame name, id, index and WebElement locator for identification

Syntax

driver.switchTo().frames();                  // Switch to window to frame

driver.switchTo().defaultContent();  // Switch to Frame to window

If we know the total number of frames in the web page, then we can use “index”. Index values help to easily switch between frames. Index will start from Zero i.e. if web page has only one frame then its index will be Zero.

         If we don’t know the number of frames the we can use “findElementBytabname()” method

        Syntax: –

                                      try

{

driver.switchTo().frame(indexnumber);

}

                                      catch(NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

We have use try and catch if now frame will not available this throw exception  .      .  .          NoSuchFrameException()

Use name as locater to find frame

Syntax: –

                  try

{

driver.switchTo().frame(“frameName”);

}

                    catch(NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

Use WebElement for switching frame

                Syntax: –

               try

{

WebElement button=driver.findElement(By.xpath(“”));

driver.switchTo().frame(button);

}

              catch (NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

Question: -What is difference between (page object model) pom and pagefactory?

Answer: –

Page Object Model (POM)

Page Factory

POM is a Design pattern which segregate selenium code based on pages.

Ex: Create a separate java class for Login page , one more class for Home Page etc.

Advanced concept ( POM + new features )or

1. Elements are identified using @FindBy or @FindBys Annotation

2. Initialism all the elements declared in Point#1 at a time.

( in POM, initialization happens on the fly )

PageFactory.initElements(driver,this);

A Page Object Model is a way of representing an application in a test framework. For every ‘page’ in the application you create a Page Object to reference the ‘page’.

A Page Factory is one way of implementing a Page Object Model. In order to support the Page Object pattern, WebDriver’s support library contains a factory class.

 

Question: – What are challenges that you faced while automating test cases?

Answer: – Two types of challenges tester have to face one is technical and another is non-technical.

Technically

There are four common issues in test automation that are: –

Wait time issues.

Ifream issues

Pop-up issues

Issues in locating deeply nested elements.

Note: – Depend on which tool you are going to use/ using, the ways to solve might different.

Non-Technically

Real Challenges comes in front of tester when client changes his requirement.

Time pressure and Deadlines.

Testing complete application.

Automate everything

Network unavailability

Understanding company, client, and end-user expectations.

Deciding when can testing should stop and how much testing coverage is enough.

Find masked bugs.

Receiving Management approval.

Selecting and using the appropriate tools.

Recognising a starting strategy.

Making realistic expectations for automation.

 

Question: -There is a submit button in page it has id property. By using “id” we got “element not found expectation”, how will you handle this situation? What might be the problem in this case?

Answer: – In this situation, there are mainly two reasons that are:-

ID is not matching

ID is changing each time when load the page.

So to handle this situation instead of using find element by Id, we can use find element by Xpath.

Question: – If submit button contain in one of 3 frames in page, how will you handle this case?

Answer: – We can handle this problem by using SwitchTo() command.

 

Question: – If element is loaded by taking much time how to handle this situation in selenium.

Answer: – Using Wait can handle this situation in selenium.

 

Question: – What is the problem with Thread.Sleep in code?

Answer: – Theard.sleep() introduces a definite wait(that is fixed periods of inactivity) no matter what happens, which will slow down our test, and if you are using CI(Continuous integration) generally result take much time if we use it all over the place.

Secondly most people who use it end up doing so because they don’t understand a problem so it’s quick and easy to just throw in an arbitrary wait rather than trying to understand the problem and fix it.

For Example: – If we do an AJAX action and then have to wait for an element to appear, the correct thing to do would be to scan for the element until it appears, the correct thing to do would be to scan for the element until it appears and then carry on, but this is harder to code than to just throw in a 30 second wait so people use a Thread.seelp() instead.

Now the problem is that this means you don’t really know why the test has failed if the element is not picked up after your 30 second time out, is it because the element didn’t appear at all, or is it because the AJAX call took longer than normal to return?

If you had some code that scanned for the element you could stick in a much longer timeout secure in the knowledge that you are not slowing your test down, and also secure in the knowledge that when it fails you can be sure that it is because the element didn’t return.

I’m sure people will argue that it is easier to use Thread.sleep() and the difference in results as described above is not that great, but when you have 200 scripts getting run in CI and each one has about 5 Thread.sleeep() calls you’ll see how much pain just throwing in a Thread.sleep() can cause.

 

Question: – What is the concept of selenium grid?

Answer: – Selenium-Grid allows you run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.

 

Question: – When we execute test cases in grid where results will be stored in node or hub?

Answer: – Selenium and Grid is installed on hub, and they are not installed on nodes. Nodes contain only he jar files. So the result will be stored in hub

 

Question: – Difference b/w quit and close?

Answer: – close() command closes the Browser window which is in focus. If there are more than one Browser window opened by the Selenium Automation, then the close( ) command will only close the Browser window which is having focus at that time. It won’t close the remaining Browser windows.

Whereas quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

If Selenium Automation opens only single Browser window the close() and quit() commands work in the similar way. But when there are more than one Browser windows opened by the Selenium Automation they work differently.

 

Question: – Manually you opened a Firefox browser window with Gmail login, now with selenium you opened a Firefox browser window with Facebook login, what happens when we use quit method? Will it closes all windows including Gmail one?

Answer: – quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

So it will close only Firefox browser window with Facebook login.

 

Question: – What all annotations used in TestNG ?

Answer: – Total 15 annotations are used in TestNG

@BeforeSuite: – The annotated method will be run only once before all tests in this suite have run.@AfterSuite: – The annotated method will be run only once after all tests in this suite have run.@BeforeClass: – The annotated method will be run only once before the first test method in the current class is invoked.@AfterClass: – The annotated method will be run only once after all the test methods in the current class have run.@BeforeTest: – The annotated method will be run before any test method belonging to the classes inside the tag is run.@AfterTest: – The annotated method will be run after all the test methods belonging to the classes inside the tag have run.@BeforeGroups: – The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.@AfterGroups: – The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.@BeforeMethod: – The annotated method will be run before each test method.@AfterMethod: – The annotated method will be run after each test method.@DataProvider: – Marks a method as supplying data for a test method. The annotated method must return an Object [ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.@Factory: – Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].@Listeners: – Defines listeners on a test class.@Parameters: – Describes how to pass parameters to a @Test method.@Test: – Marks a class or a method as a part of the test.

 

Question: – If we want to do DataDriven with TestNG, which annotations required?

Answer: – TestNG @DataProvider Annotation is required for DataDriven with TestNG. @DataProvider Annotation of TestNG framework provides us a facility of storing and preparing data set in method. Task of @DataProvider annotated method is supplying data for a test method. Means you can configure data set in that method and then use that data In your test method. @DataProvider annotated method must return an Object[][] with data.

 

Question: – Is it possible to pass test data through testng.xml file, if yes how?

Answer: – Yes it is possible to pass test data through XML file by using @Parameters annotations

To do so, you will need to

Create an XML file which will store the parametersIn the test, add annotation @Parameters

XML File



Selenium Scripting

@Test

@Parameters({“author”,”searchKey”})

public void testParameterWithXML(@Optional(“ABC”)String author,String searchKey)throws InterruptedException{}

Note: -There are mainly two ways through which we can provide parameter values to test-methods: One is through testng.xml XML configuration file and through DataProviders.

Question: – How to run specific kind of Test cases using TestNG?

Answer: – Three ways we can run Test Cases using TestNG

On an existing testng.xml.On a synthetic testng.xml, created entirely from Java.By directly setting the test classes.

 

Question: – How to prioritize test cases in TestNG?

Answer: – In TestNG “Priority” is used to schedule the test cases.at is we can execute Test case in order.  In order to achive, we use need to add annotation as @Test(priority=??). The default value will be zero for priority.

If you don’t mention the priority, it will take all the test cases as “priority=0” and execute.

If we define priority as “priority=”, these test cases will get executed only when all the test cases which don’t have any priority as the default priority will be set to “priority=0”

 

Question: – What are all interfaces available in selenium?

Answer: –

InterfaceDescriptionAlertCapabilitiesDescribes a series of key/value pairs that encapsulate aspect of a browserContextAwareSome implementations of WebDriver, notably those that support native testing, need the ability to switch between the native and web-based contexts.HasCapabilitiesUsed by classes to indicate that they can describe the capabilities they possess.JavascriptExecutorIndicates that a driver can execute JavaScript, providing access to the mechanism to do so.OutputTypeDefines the output type for a screenshot.RotatableRepresents rotation of the browser view for orientation – sensitive devices.SearchContextTakeScreenshotIndicates a driver that can capture a screenshot and store it in different ways.WebDriverThe main interface to use for testing, which represents an idealised web browserWebDriver.ImeHandlerWebDriver.OptionsAn Interface for managing stuff you would do in a browser menuWebDriver.TargetLocatorUsed to locate a given frame or window.WebDriver.TimeoutsAn interface for managing timeout behaviour for WebDriver instanceWebDriver.WindowWebElementRepersents an HTML element.

 

Question: – Action is class or interface?

Answer: – Action is an interface.

Use to perform Advanced User Interactions, like drag and drop, keyboard events; selenium came up with Action and Actions interface under a comprehensive API, named as Advanced User Interaction which facilitates user actions to be performed on an application. Thus users can use this API to simulate usage of keyboard or mouse events.

Example:-

To double-click a control we have DoubleClick(), method of Actions Class.

To Send keyboard actions, we have SendKeys() ,method.(Equivalent to WebElement.sendKey(…))

Clicking the mouse button that brings up the contextual menu.we can use “ContextClick()”, method.

Package:-

import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

Syntax:-

Actions oAction=new Actions(selenium);

oAction.contextClick(element).perform();

 

Question: – Why we using TestNG? What are benefits we get using TestNG? Can we execute test cases in order without using TestNG?

Answer: – WHY We Using TestNG

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionality that make it more powerful and easier to use, such as:

Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc…).

Test that your code is multithread safe.

Flexible test configuration.

Support for data-driven testing (with @DataProvider).

Support for parameters.

Powerful execution model (no more TestSuite).

Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc…).

Embeds BeanShell for further flexibility.

Default JDK functions for runtime and logging (no dependencies).

Dependent methods for application server testing.

TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc…

Advantages of TestNG

TestNG allows us to execute of test cases based on group.

TestNG annotations are easy to understand.

Parallel execution of selenium test cases is possible in TestNG.

Three kinds of report generated.

Order of execution can be change using TestNG

Failed test cases can be executed.

Without having main function we can execute the test method.

An xml file can be execution order and we can skip the execution of particular test case.

Can we execute test cases in order without using TestNG

 Yes, we execute test cases in order without using TestNG with the help of Junit

 

Question: – Explain polymorphism in java.

Answer: – Polymorphism means ‘many forms’. In OOP, polymorphism means a type can point to different object at different time. In other words, the actual object to which a reference type refers can be determined at runtime.

In Java, polymorphism is based on inheritance and overriding.

Polymorphism is a robust feature of OOP. It increases the reusability, flexibility and extensibility of code.

 

Question: -There are two methods in same class with same name with different arguments and different access modifiers like

 public void m1(int a){}

 private void m1(string b){}

 Is it overloading or not?

Answer: – Overloading allows different methods to have same name, but different signatures where signature can differ by number of input/output parameters or type of input/output parameters or both.

So yes this is overloading.

 

Question: – What are types of inheritance in java?

Answer: -Single Inheritance, Multi-Level Inheritance and Hierarchical Inheritance.

 

Question: – Is multiple inheritance is possible in java? Reasons?

Answer: – To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

 

Question: – Is multilevel inheritance is possible in java? Give reason.

Answer: – A class can implement multiple interfaces. Object class is not an example of multiple inheritance. May be you misinterpreted the question. The answer is Java supports multi-level inheritance but not multiple inheritance.

 

Question: – There are 10 pages in same window; an image is present in any page out of ten pages in same window. How will you validate this scenario?

Answer: – Get the total numbers of frames on a webpage base on that have a for loop and switchTo() all frame one by one and check if image is present then come out of  that frame and again switch to next frame, continue this till you get image then break the loop.

Question: – How to check image is loaded correctly or not in page?

Answer:
WebElement image1 = driver.findElement(By.xpath(“//div[contains(@class,’global-header__brand’)]”));

Boolean imageLoaded1 = (Boolean) ((JavascriptExecutor)driver).executeScript(“return arguments[0].complete && typeof arguments[0].naturalWidth != “undefined” && arguments[0].naturalWidth > 0″, image1);

if (!imageLoaded1)

{

System.out.println(“1. Image is not present”);

}

else

{

System.out.println(“1. Got it”);

}

 

Question: – What is the purpose of Sikuli?

Answer: -Sikuli automates anything you see on screen using the image recognition method to identify GUI elements. Sikuli script allows users to automate GUI interaction by using screenshots.

 

Question: – Is it possible to compare two images with Sikuli?

Answer: – Yes

 

Question: – How to check webpage is fully loaded or not using Selenium?

Answer: – This situation can be solved by using JavaScript executors.

IWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript(“return document.readyState”).Equals(“complete”));

 

Question: – Write a code for DB connection.

Answer: – Creating SQL & MySQL Connections:

package util;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

public class DbManager

{

private static Connection con = null;

private static Connection conn = null;

// Database connection for SQL Server

public static void setDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try{

Class.forName(TestConfig.driver);

con =   DriverManager.getConnection(dbConnectionUrl, dbUserName, dbPassword);

if(!con.isClosed())

System.out.println(“Successfully connected to SQL server”);

}catch(Exception e){

System.err.println(“Exception: ” + e.getMessage());

}       }

public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try

{

Class.forName (TestConfig.mysqldriver).newInstance ();

conn = DriverManager.getConnection (mysqlurl, mysqluserName, mysqlpassword);

if(!conn.isClosed())

System.out.println(“Successfully connected to MySQL server”);

}

catch (Exception e)

{

System.err.println (“Cannot connect to database server”);

}

}

// Query list for SQL

public static List getQuery(String query) throws SQLException

{

Statement St = con.createStatement();

ResultSet rs = St.executeQuery(query);

List values = new ArrayList();

while(rs.next()){

values.add(rs.getString(1));

}

return values;

}

// Query list for MySQL

public static List getMysqlQuery(String query) throws SQLException

{

Statement St = conn.createStatement();

ResultSet rs = St.executeQuery(query);

List values1 = new ArrayList();

while(rs.next()){

values1.add(rs.getString(1));

}

return values1;

}

 

Question: – How do you handle exception handling in selenium?

Answer: – Same Try Catch like used in java.

 

Question: – Explain run time and compile time polymorphism.

Answer: – Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.

Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.

Compile time PolymorphismRun time PolymorphismIn Compile time Polymorphism, call is resolved by the compiler.In Run time Polymorphism, call is not resolved by the compiler.It is also known as Static binding, Early binding and overloading as well.It is also known as Dynamic binding, Late binding and overriding as well.Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.It is achieved by function overloading and operator overloading.It is achieved by virtual functions and pointers.It provides fast execution because known early at compile time.It provides slow execution as compare to early binding because it is known at runtime

 

Question: – Write a code for multiple handling windows?

Answer: –

public void test() throws Exception {
// Opening site
driver.findElement(By.xpath(“//img[@alt=’SeleniumMasterLogo’]”)).click();
// Storing parent window reference into a String Variable
String Parent_Window = driver.getWindowHandle();
// Switching from parent window to child window
for (String Child_Window : driver.getWindowHandles())
{
driver.switchTo().window(Child_Window);
// Performing actions on child window
driver.findElement(By.id(“dropdown_txt”)).click();
List  dropdownitems=driver.findElements(By.xpath(“//div[@id=’DropDownitems’]//div”));
int dropdownitems_Size=dropdownitems.size();
System.out.println(“Dropdown item size is:”+dropdownitems_Size);
((WebElement) dropdownitems.get(1)).click();
driver.findElement(By.xpath(“//*[@id=’anotherItemDiv’]”)).click();
}
//Switching back to Parent Window
driver.switchTo().window(Parent_Window);
//Performing some actions on Parent Window
driver.findElement(By.className(“btn_style”)).click();
}

 

Question: -How do you handle synchronization in selenium?

Answer: – By using wait we can handle synchronization in Selenium.

 

Question: – Why do we need Software Testing Metrics?

Answer: – Metrics provide insight into the project’s status in relation to predefined goals.    It is important to measure the efficiency and effectiveness of the Test processes. Without metrics, how would you know that everything is right OR something needs your attention!

Helps in decision-making for next phase of activities, process or technology change.

Easy for management to digest one number and drill down, if required.

Different Metric(s) trends act as monitor when the process is going out-of-control.

Evidence of the claim or prediction.

Help us judge how efficient the testing efforts are.

Make proactive and informed decisions

 

Question: – 7 Soft skills every ‘QA Tester’ needs:

Answer:

Know how to ask the right questions, and when to ask them

Know how to listen

Know how to focus on what business stakeholders care about … and forget the rest

Know how to play well with others: Take a developer to lunch

Know how to deal with bullies

Know how to manage your time effectively

Know how to trust your judgment — and your intuition

 

Question: – What is the most challenging situation you have had in your Testing experience?

Answer: – As you might have guessed, it depends on each tester’s experience. The challenge can be technical, process-oriented, people’s related, domain specific OR anything within your Testing experience. For me,

Testing a technically-challenging application such as social-connected applications, application involving multiple third-party interfaces, cloud-big data-IoT-Analytics-etc. applications.

Maintaining a balance between design/execution efficiency and defect detection. Improving the Test coverage. Sticking to agile principles.

Resources on unplanned leaves, some even abscond. Estimation gone wrong, requiring weekend & extended working hours. Rating discussions with unhappy employees.

A team of fresher’s with limited domain knowledge. Planning for knowledge transfer sessions. The thumb rule – be realistic & tell your genuine challenges!

 

Question: – What is Automation and Manual Testing?

Answer: –

Automation: Software testing method which uses automation software, tools and scripts to run tests that repeat predefined actions, matches the developed program’s probable and real results.

Manual: The process of manual software testing involves manually running the individual tests or tasks associated with a product without the aid of scripts or other tools, in order to identify bugs or other issues. During this process, the testing team will use the application from end-user perspective.

 

Question: – How generate user defined exceptions, write syntax?

Answer: –

class MyException extends Exception

{

String s1;

MyException(String s2)

{      s1 = s2;   }

@Override

public String toString()

{

return (“Output String = “+s1);

}

}

public class NewClass

{

public static void main(String args[])

{

try

{

throw new MyException(“Custom message”);

}

catch(MyException exp)

{

System.out.println(exp);     ‘

}

}

}

 

Question: – Difference between throw and throws keyword?

Answer: –

throwthrowsJava throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.Throw is followed by an instance.Throws is followed by class.Throw is used within the method.Throws is used with the method signature.You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
Not sure  Hyderabad, India    Yes
Selenium Selenium Automation Testing Real world Interview Question and Answer

 

Question: – How to switch from frame to main window? With syntax.

Answer: – We can give frame name, id, index and WebElement locator for identification

Syntax

driver.switchTo().frames();                  // Switch to window to frame

driver.switchTo().defaultContent();  // Switch to Frame to window

If we know the total number of frames in the web page, then we can use “index”. Index values help to easily switch between frames. Index will start from Zero i.e. if web page has only one frame then its index will be Zero.

         If we don’t know the number of frames the we can use “findElementBytabname()” method

        Syntax: –

                                      try

{

driver.switchTo().frame(indexnumber);

}

                                      catch(NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

We have use try and catch if now frame will not available this throw exception  .      .  .          NoSuchFrameException()

Use name as locater to find frame

Syntax: –

                  try

{

driver.switchTo().frame(“frameName”);

}

                    catch(NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

Use WebElement for switching frame

                Syntax: –

               try

{

WebElement button=driver.findElement(By.xpath(“”));

driver.switchTo().frame(button);

}

              catch (NoSuchFrameException e)

{

System.out.println(e.getMessage());

}

Question: -What is difference between (page object model) pom and pagefactory?

Answer: –

Page Object Model (POM)

Page Factory

POM is a Design pattern which segregate selenium code based on pages.

Ex: Create a separate java class for Login page , one more class for Home Page etc.

Advanced concept ( POM + new features )or

1. Elements are identified using @FindBy or @FindBys Annotation

2. Initialism all the elements declared in Point#1 at a time.

( in POM, initialization happens on the fly )

PageFactory.initElements(driver,this);

A Page Object Model is a way of representing an application in a test framework. For every ‘page’ in the application you create a Page Object to reference the ‘page’.

A Page Factory is one way of implementing a Page Object Model. In order to support the Page Object pattern, WebDriver’s support library contains a factory class.

 

Question: – What are challenges that you faced while automating test cases?

Answer: – Two types of challenges tester have to face one is technical and another is non-technical.

Technically

There are four common issues in test automation that are: –

Wait time issues.

Ifream issues

Pop-up issues

Issues in locating deeply nested elements.

Note: – Depend on which tool you are going to use/ using, the ways to solve might different.

Non-Technically

Real Challenges comes in front of tester when client changes his requirement.

Time pressure and Deadlines.

Testing complete application.

Automate everything

Network unavailability

Understanding company, client, and end-user expectations.

Deciding when can testing should stop and how much testing coverage is enough.

Find masked bugs.

Receiving Management approval.

Selecting and using the appropriate tools.

Recognising a starting strategy.

Making realistic expectations for automation.

 

Question: -There is a submit button in page it has id property. By using “id” we got “element not found expectation”, how will you handle this situation? What might be the problem in this case?

Answer: – In this situation, there are mainly two reasons that are:-

ID is not matching

ID is changing each time when load the page.

So to handle this situation instead of using find element by Id, we can use find element by Xpath.

Question: – If submit button contain in one of 3 frames in page, how will you handle this case?

Answer: – We can handle this problem by using SwitchTo() command.

 

Question: – If element is loaded by taking much time how to handle this situation in selenium.

Answer: – Using Wait can handle this situation in selenium.

 

Question: – What is the problem with Thread.Sleep in code?

Answer: – Theard.sleep() introduces a definite wait(that is fixed periods of inactivity) no matter what happens, which will slow down our test, and if you are using CI(Continuous integration) generally result take much time if we use it all over the place.

Secondly most people who use it end up doing so because they don’t understand a problem so it’s quick and easy to just throw in an arbitrary wait rather than trying to understand the problem and fix it.

For Example: – If we do an AJAX action and then have to wait for an element to appear, the correct thing to do would be to scan for the element until it appears, the correct thing to do would be to scan for the element until it appears and then carry on, but this is harder to code than to just throw in a 30 second wait so people use a Thread.seelp() instead.

Now the problem is that this means you don’t really know why the test has failed if the element is not picked up after your 30 second time out, is it because the element didn’t appear at all, or is it because the AJAX call took longer than normal to return?

If you had some code that scanned for the element you could stick in a much longer timeout secure in the knowledge that you are not slowing your test down, and also secure in the knowledge that when it fails you can be sure that it is because the element didn’t return.

I’m sure people will argue that it is easier to use Thread.sleep() and the difference in results as described above is not that great, but when you have 200 scripts getting run in CI and each one has about 5 Thread.sleeep() calls you’ll see how much pain just throwing in a Thread.sleep() can cause.

 

Question: – What is the concept of selenium grid?

Answer: – Selenium-Grid allows you run your tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.

 

Question: – When we execute test cases in grid where results will be stored in node or hub?

Answer: – Selenium and Grid is installed on hub, and they are not installed on nodes. Nodes contain only he jar files. So the result will be stored in hub

 

Question: – Difference b/w quit and close?

Answer: – close() command closes the Browser window which is in focus. If there are more than one Browser window opened by the Selenium Automation, then the close( ) command will only close the Browser window which is having focus at that time. It won’t close the remaining Browser windows.

Whereas quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

If Selenium Automation opens only single Browser window the close() and quit() commands work in the similar way. But when there are more than one Browser windows opened by the Selenium Automation they work differently.

 

Question: – Manually you opened a Firefox browser window with Gmail login, now with selenium you opened a Firefox browser window with Facebook login, what happens when we use quit method? Will it closes all windows including Gmail one?

Answer: – quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

So it will close only Firefox browser window with Facebook login.

 

Question: – What all annotations used in TestNG ?

Answer: – Total 15 annotations are used in TestNG

@BeforeSuite: – The annotated method will be run only once before all tests in this suite have run.@AfterSuite: – The annotated method will be run only once after all tests in this suite have run.@BeforeClass: – The annotated method will be run only once before the first test method in the current class is invoked.@AfterClass: – The annotated method will be run only once after all the test methods in the current class have run.@BeforeTest: – The annotated method will be run before any test method belonging to the classes inside the tag is run.@AfterTest: – The annotated method will be run after all the test methods belonging to the classes inside the tag have run.@BeforeGroups: – The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.@AfterGroups: – The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.@BeforeMethod: – The annotated method will be run before each test method.@AfterMethod: – The annotated method will be run after each test method.@DataProvider: – Marks a method as supplying data for a test method. The annotated method must return an Object [ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.@Factory: – Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].@Listeners: – Defines listeners on a test class.@Parameters: – Describes how to pass parameters to a @Test method.@Test: – Marks a class or a method as a part of the test.

 

Question: – If we want to do DataDriven with TestNG, which annotations required?

Answer: – TestNG @DataProvider Annotation is required for DataDriven with TestNG. @DataProvider Annotation of TestNG framework provides us a facility of storing and preparing data set in method. Task of @DataProvider annotated method is supplying data for a test method. Means you can configure data set in that method and then use that data In your test method. @DataProvider annotated method must return an Object[][] with data.

 

Question: – Is it possible to pass test data through testng.xml file, if yes how?

Answer: – Yes it is possible to pass test data through XML file by using @Parameters annotations

To do so, you will need to

Create an XML file which will store the parametersIn the test, add annotation @Parameters

XML File



Selenium Scripting

@Test

@Parameters({“author”,”searchKey”})

public void testParameterWithXML(@Optional(“ABC”)String author,String searchKey)throws InterruptedException{}

Note: -There are mainly two ways through which we can provide parameter values to test-methods: One is through testng.xml XML configuration file and through DataProviders.

Question: – How to run specific kind of Test cases using TestNG?

Answer: – Three ways we can run Test Cases using TestNG

On an existing testng.xml.On a synthetic testng.xml, created entirely from Java.By directly setting the test classes.

 

Question: – How to prioritize test cases in TestNG?

Answer: – In TestNG “Priority” is used to schedule the test cases.at is we can execute Test case in order.  In order to achive, we use need to add annotation as @Test(priority=??). The default value will be zero for priority.

If you don’t mention the priority, it will take all the test cases as “priority=0” and execute.

If we define priority as “priority=”, these test cases will get executed only when all the test cases which don’t have any priority as the default priority will be set to “priority=0”

 

Question: – What are all interfaces available in selenium?

Answer: –

InterfaceDescriptionAlertCapabilitiesDescribes a series of key/value pairs that encapsulate aspect of a browserContextAwareSome implementations of WebDriver, notably those that support native testing, need the ability to switch between the native and web-based contexts.HasCapabilitiesUsed by classes to indicate that they can describe the capabilities they possess.JavascriptExecutorIndicates that a driver can execute JavaScript, providing access to the mechanism to do so.OutputTypeDefines the output type for a screenshot.RotatableRepresents rotation of the browser view for orientation – sensitive devices.SearchContextTakeScreenshotIndicates a driver that can capture a screenshot and store it in different ways.WebDriverThe main interface to use for testing, which represents an idealised web browserWebDriver.ImeHandlerWebDriver.OptionsAn Interface for managing stuff you would do in a browser menuWebDriver.TargetLocatorUsed to locate a given frame or window.WebDriver.TimeoutsAn interface for managing timeout behaviour for WebDriver instanceWebDriver.WindowWebElementRepersents an HTML element.

 

Question: – Action is class or interface?

Answer: – Action is an interface.

Use to perform Advanced User Interactions, like drag and drop, keyboard events; selenium came up with Action and Actions interface under a comprehensive API, named as Advanced User Interaction which facilitates user actions to be performed on an application. Thus users can use this API to simulate usage of keyboard or mouse events.

Example:-

To double-click a control we have DoubleClick(), method of Actions Class.

To Send keyboard actions, we have SendKeys() ,method.(Equivalent to WebElement.sendKey(…))

Clicking the mouse button that brings up the contextual menu.we can use “ContextClick()”, method.

Package:-

import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

Syntax:-

Actions oAction=new Actions(selenium);

oAction.contextClick(element).perform();

 

Question: – Why we using TestNG? What are benefits we get using TestNG? Can we execute test cases in order without using TestNG?

Answer: – WHY We Using TestNG

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionality that make it more powerful and easier to use, such as:

Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc…).

Test that your code is multithread safe.

Flexible test configuration.

Support for data-driven testing (with @DataProvider).

Support for parameters.

Powerful execution model (no more TestSuite).

Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc…).

Embeds BeanShell for further flexibility.

Default JDK functions for runtime and logging (no dependencies).

Dependent methods for application server testing.

TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc…

Advantages of TestNG

TestNG allows us to execute of test cases based on group.

TestNG annotations are easy to understand.

Parallel execution of selenium test cases is possible in TestNG.

Three kinds of report generated.

Order of execution can be change using TestNG

Failed test cases can be executed.

Without having main function we can execute the test method.

An xml file can be execution order and we can skip the execution of particular test case.

Can we execute test cases in order without using TestNG

 Yes, we execute test cases in order without using TestNG with the help of Junit

 

Question: – Explain polymorphism in java.

Answer: – Polymorphism means ‘many forms’. In OOP, polymorphism means a type can point to different object at different time. In other words, the actual object to which a reference type refers can be determined at runtime.

In Java, polymorphism is based on inheritance and overriding.

Polymorphism is a robust feature of OOP. It increases the reusability, flexibility and extensibility of code.

 

Question: -There are two methods in same class with same name with different arguments and different access modifiers like

 public void m1(int a){}

 private void m1(string b){}

 Is it overloading or not?

Answer: – Overloading allows different methods to have same name, but different signatures where signature can differ by number of input/output parameters or type of input/output parameters or both.

So yes this is overloading.

 

Question: – What are types of inheritance in java?

Answer: -Single Inheritance, Multi-Level Inheritance and Hierarchical Inheritance.

 

Question: – Is multiple inheritance is possible in java? Reasons?

Answer: – To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

 

Question: – Is multilevel inheritance is possible in java? Give reason.

Answer: – A class can implement multiple interfaces. Object class is not an example of multiple inheritance. May be you misinterpreted the question. The answer is Java supports multi-level inheritance but not multiple inheritance.

 

Question: – There are 10 pages in same window; an image is present in any page out of ten pages in same window. How will you validate this scenario?

Answer: – Get the total numbers of frames on a webpage base on that have a for loop and switchTo() all frame one by one and check if image is present then come out of  that frame and again switch to next frame, continue this till you get image then break the loop.

Question: – How to check image is loaded correctly or not in page?

Answer:
WebElement image1 = driver.findElement(By.xpath(“//div[contains(@class,’global-header__brand’)]”));

Boolean imageLoaded1 = (Boolean) ((JavascriptExecutor)driver).executeScript(“return arguments[0].complete && typeof arguments[0].naturalWidth != “undefined” && arguments[0].naturalWidth > 0″, image1);

if (!imageLoaded1)

{

System.out.println(“1. Image is not present”);

}

else

{

System.out.println(“1. Got it”);

}

 

Question: – What is the purpose of Sikuli?

Answer: -Sikuli automates anything you see on screen using the image recognition method to identify GUI elements. Sikuli script allows users to automate GUI interaction by using screenshots.

 

Question: – Is it possible to compare two images with Sikuli?

Answer: – Yes

 

Question: – How to check webpage is fully loaded or not using Selenium?

Answer: – This situation can be solved by using JavaScript executors.

IWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript(“return document.readyState”).Equals(“complete”));

 

Question: – Write a code for DB connection.

Answer: – Creating SQL & MySQL Connections:

package util;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

public class DbManager

{

private static Connection con = null;

private static Connection conn = null;

// Database connection for SQL Server

public static void setDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try{

Class.forName(TestConfig.driver);

con =   DriverManager.getConnection(dbConnectionUrl, dbUserName, dbPassword);

if(!con.isClosed())

System.out.println(“Successfully connected to SQL server”);

}catch(Exception e){

System.err.println(“Exception: ” + e.getMessage());

}       }

public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try

{

Class.forName (TestConfig.mysqldriver).newInstance ();

conn = DriverManager.getConnection (mysqlurl, mysqluserName, mysqlpassword);

if(!conn.isClosed())

System.out.println(“Successfully connected to MySQL server”);

}

catch (Exception e)

{

System.err.println (“Cannot connect to database server”);

}

}

// Query list for SQL

public static List getQuery(String query) throws SQLException

{

Statement St = con.createStatement();

ResultSet rs = St.executeQuery(query);

List values = new ArrayList();

while(rs.next()){

values.add(rs.getString(1));

}

return values;

}

// Query list for MySQL

public static List getMysqlQuery(String query) throws SQLException

{

Statement St = conn.createStatement();

ResultSet rs = St.executeQuery(query);

List values1 = new ArrayList();

while(rs.next()){

values1.add(rs.getString(1));

}

return values1;

}

 

Question: – How do you handle exception handling in selenium?

Answer: – Same Try Catch like used in java.

 

Question: – Explain run time and compile time polymorphism.

Answer: – Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.

Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.

Compile time PolymorphismRun time PolymorphismIn Compile time Polymorphism, call is resolved by the compiler.In Run time Polymorphism, call is not resolved by the compiler.It is also known as Static binding, Early binding and overloading as well.It is also known as Dynamic binding, Late binding and overriding as well.Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.It is achieved by function overloading and operator overloading.It is achieved by virtual functions and pointers.It provides fast execution because known early at compile time.It provides slow execution as compare to early binding because it is known at runtime

 

Question: – Write a code for multiple handling windows?

Answer: –

public void test() throws Exception {
// Opening site
driver.findElement(By.xpath(“//img[@alt=’SeleniumMasterLogo’]”)).click();
// Storing parent window reference into a String Variable
String Parent_Window = driver.getWindowHandle();
// Switching from parent window to child window
for (String Child_Window : driver.getWindowHandles())
{
driver.switchTo().window(Child_Window);
// Performing actions on child window
driver.findElement(By.id(“dropdown_txt”)).click();
List  dropdownitems=driver.findElements(By.xpath(“//div[@id=’DropDownitems’]//div”));
int dropdownitems_Size=dropdownitems.size();
System.out.println(“Dropdown item size is:”+dropdownitems_Size);
((WebElement) dropdownitems.get(1)).click();
driver.findElement(By.xpath(“//*[@id=’anotherItemDiv’]”)).click();
}
//Switching back to Parent Window
driver.switchTo().window(Parent_Window);
//Performing some actions on Parent Window
driver.findElement(By.className(“btn_style”)).click();
}

 

Question: -How do you handle synchronization in selenium?

Answer: – By using wait we can handle synchronization in Selenium.

 

Question: – Why do we need Software Testing Metrics?

Answer: – Metrics provide insight into the project’s status in relation to predefined goals.    It is important to measure the efficiency and effectiveness of the Test processes. Without metrics, how would you know that everything is right OR something needs your attention!

Helps in decision-making for next phase of activities, process or technology change.

Easy for management to digest one number and drill down, if required.

Different Metric(s) trends act as monitor when the process is going out-of-control.

Evidence of the claim or prediction.

Help us judge how efficient the testing efforts are.

Make proactive and informed decisions

 

Question: – 7 Soft skills every ‘QA Tester’ needs:

Answer:

Know how to ask the right questions, and when to ask them

Know how to listen

Know how to focus on what business stakeholders care about … and forget the rest

Know how to play well with others: Take a developer to lunch

Know how to deal with bullies

Know how to manage your time effectively

Know how to trust your judgment — and your intuition

 

Question: – What is the most challenging situation you have had in your Testing experience?

Answer: – As you might have guessed, it depends on each tester’s experience. The challenge can be technical, process-oriented, people’s related, domain specific OR anything within your Testing experience. For me,

Testing a technically-challenging application such as social-connected applications, application involving multiple third-party interfaces, cloud-big data-IoT-Analytics-etc. applications.

Maintaining a balance between design/execution efficiency and defect detection. Improving the Test coverage. Sticking to agile principles.

Resources on unplanned leaves, some even abscond. Estimation gone wrong, requiring weekend & extended working hours. Rating discussions with unhappy employees.

A team of fresher’s with limited domain knowledge. Planning for knowledge transfer sessions. The thumb rule – be realistic & tell your genuine challenges!

 

Question: – What is Automation and Manual Testing?

Answer: –

Automation: Software testing method which uses automation software, tools and scripts to run tests that repeat predefined actions, matches the developed program’s probable and real results.

Manual: The process of manual software testing involves manually running the individual tests or tasks associated with a product without the aid of scripts or other tools, in order to identify bugs or other issues. During this process, the testing team will use the application from end-user perspective.

 

Question: – How generate user defined exceptions, write syntax?

Answer: –

class MyException extends Exception

{

String s1;

MyException(String s2)

{      s1 = s2;   }

@Override

public String toString()

{

return (“Output String = “+s1);

}

}

public class NewClass

{

public static void main(String args[])

{

try

{

throw new MyException(“Custom message”);

}

catch(MyException exp)

{

System.out.println(exp);     ‘

}

}

}

 

Question: – Difference between throw and throws keyword?

Answer: –

throwthrowsJava throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.Throw is followed by an instance.Throws is followed by class.Throw is used within the method.Throws is used with the method signature.You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.
Test Hyderabad  Test Yes
Selenium, TestNG, Cucumber GAURAV CHAUBEY DXC Bangalore   Yes
Selenium 1. How will you find a dynamic value in a webtable? The webtable dont have pagination, new values are displayed as user scroll down the page

2.What is the best way to pass output of one test method to another test method in Nunit/Xunit
Optum-Hyderabad India   Yes
Selenium, Maven 1. what is Thread.cleep()?
2.Difference between absolue xpath and relative xpath?
3. How do you write on excel sheet?
4. What are the asserts used? Expain.
5. Why do you prefer xpath over css selector?
6. what is pom.xml in maven? (full form)
7. Which framework did you use? Explain?
8. How do you navigate from one page to other?
9. If you want to reach the bottom by scrolling the page, how you do it in selenium?
Mindtree, Bangalore Bangalore,India   Maybe
Selenium, API/BackEnd 1.How do you choose which automation tool suites to your application?
2.when do you not prefer automation?
United Airlines, Texas Austin,Tx    No
Jenkins, Maven, Not Listed here 1. Implement threadsafe Singleton class
2. First non repeating character in liner time.
3. Explain (as per my exeperince) how JVM manages memory.
4. Internal working of linkedHashMap
5. what if locally all test cases are good but on jenkins fails. How to debug this.
6. Find the occurance of character in sorted roated array.
7. how to set git head
8. maven .m2 folder( how it manages repository if 10 projects are there)
9. Idempotent rest calls.
10. Why @cahchelookup in selenium factory
11.tell me a situation when you had conflicts
12. tell me a situation when i took lead in project
AJIO, Banglore Gurgaon I enjoyed coding with optimization. I got stuck on maven repo managemet but he helped me  Yes
Not Listed here Please list out the SOLID principles .How would you implement SOLID principles in your test automation framework? I have framed this question because of current experience in my project India   Maybe
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber, Not Listed here Rajendra Singh Deleoit Gury   No
Selenium, GIT/Bitbucket, TestNG, Cucumber Difference between abstract class and interface?

Can main method be overridden
ADP, Hyderabad Hyderabad, India   Yes
Selenium Java program to print my Full Name in Reverse order
Questions for Assertions in TestNG
Jherkin way of writing testcases
Tangerine  Toronto,Canada   Yes
Selenium, API/BackEnd, Postman, GIT/Bitbucket, WebDriverIO, TestNG Got commands, Linux commands, head and tail command, webdriver open browser command, list comprehension, lambda function, Java pseudo code to find unique element in a list, Java pseudo code to reverse an array Coviam, Bangalore; Portworkx, Bangalore Pune, India   No
Selenium, API/BackEnd, Not Listed here 1. How do you handle login page without any attributes and input tag is the only reference that can be used.
2. Without using expected class to check whether alert is displayed.
3. Design logic to check element to be present.
4. Difference between API and webservice
5. Significance of string builder and string buffer. 
Cognizant Technology Services, Synchronoss Technology  Bengaluru  1. Collect all input in collections and then using get you can call respective web element or you can write xpath with indexes.
2. Write switch to  alert in try block and set boolean value as true in it else set it false in catch
3. Check is displayed in try,set boolean true and catch no such element and set boolean false
4. API are special method whose implementation can’t be changed while web service is special type of API used to interact with different systems.. I. E all webservices are API but not all API are webservices.. eg. Selenium is also api but not webservices
5. Performance and using existing object reference can be explained 
Yes
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber Why use automation Framework. HCL noida Noida,India   Yes
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, TestNG What is implicit and explicit wait Maxdigi solutions Nashik city   No
Cucumber How do you skip the particular tag from your feature files  RBS Chennai Chennai, India Ignore tag or skip tag No
Selenium, Jenkins, Maven, TestNG 1) How to run failed test scripts
2) programs on hashmap
3) different coding programs on strings
capgemini banglore ani No
Selenium, API/BackEnd, Rest Assured, Postman, JMeter, TestNG, Cucumber What are the components of you framework? How will you differentiate between page layer and test cases and also how they are inter related. How to handle multiple windows? How to manage asynchronous request/response in restassured? Login to once application–>there are 50 links in home page–>You need to select only 1 link which will open a pdf. How you will manage chaining request in API.Given a scenario to build framework using cucumber.Challanges faced in API testing and how you have managed that. What is the use of Listners in TestNG. How you have used Listners in your project. So many questions was from Java mainly from string class, Map and Set interface. Epsilion and Hcl, Bangalore Bangalore   Yes
Selenium, API/BackEnd, Jenkins, TestNG What is the difference between final, finally and finalize?
Write a program to find the equilibrium point in an array.
Write a program to find the first repeated character in a string.
When you run your selenium automation test scripts then many temp files are created. How will you clear those temp files? –Deloitte
Suppose there is a situation that the time in which home page is loaded is not fixed. You cannot apply waits in any case. How will you start your automation? –Deloitte
After submitting the form you get error. How will you debug? –airtel

Deloitte-Bangaluru, airtel-gurgaon Gurgaon   Yes
Selenium Selenium code on frames and window handles.  CTS-Chennai Chennai, India   Yes
Selenium how will you execute only failed test cases through Jenkins, what are the exception you have faced and how have you handled those,   capegemini bangalore to add path of failed-output.xml in post condition  Yes
Selenium, GIT/Bitbucket, TestNG In your test automation career, did you face any exception if yes tell me names NIIT bangalore Bangalore, India NullPointer exception No
Selenium, GIT/Bitbucket Q1. Difference between synchronous calls and asynchronous calls while a page is loaded and how to test the same using selenium?
Q2. Can react angular applications be tested with selenium effectively?
Q3. Frameworks for testing react applications?
Q4. Highlighting a text between span, which is having 1000+ lines, and text should be selected based on index and not replacing the text?
Q5. multiple tables in nested way having same table names in react application?
Q6. Code for star patterns?
Q7. Code for using dynamic variables, which can be using in multiple test cases using data models?
GKMIT, Udaipur Udaipur, India   Yes
Selenium How did you validate data entered from the UI is consistently reflected in the database ? Equifax,Ireland Dublin,Ireland   Yes
Selenium, Jenkins, Maven, GIT/Bitbucket, TestNG 1. Is WebDriverWait a class or interface ? 2. In TDD framework, have you used jar files ? If yes, then which types jar files ? 3. In actions class,   .build().release()   what is difference b/w .build and .release ? Accenture, Gurugram, Cognizant, Bangalore Aligarh, India   No
Selenium, TestNG how many test cases you can run in a days suppose you are a one tester in company how many time you will take test all module, what types of bug found in testNg  ? What is your team size ? You developing Framework if you devdloping framework then tell me process ?  Company Name , TSYS, Location : Noida  Noida   No
Selenium, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber How to read data from Excel through hashmap where 1st row is key, remaining rows are values  CTS, Chennai Chennai,india I tried but not sure Maybe
Selenium, Rest Assured, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber Selenium, Cucumber

Q1. What is Selenium Architecture, how does selenium interacts with browser internally?
Q2. What all design patterns you followed in your framework and how?
Q3. What are Feauture files, Hooks, tagged hooks, Background keywords and their usage in Cucumber? Is there any limit to number of scenarios we can write in feature file?
Q4. How to set priority of test cases in Cucumber?
Q5. How to handle frames,  when there is no frame id, name and without xpath?
Q6. How to handle basic authentication pop-up, alert, waits?
Q7. How to verify/validate color and underscore?
Q8. Suppose there is three radio button upon selecting radio buttons dropdown appears where we have to select the values from that? How to do?
Q9. What is method overriding, overloading, abstract class and interface and their usage in your framework, hashMap usage in selenium?
Q10. Scenario based question to handle webtable with pagination?
Q11. Difference b/w getAttribute() and getText()?
Q12 . How to verify broken links and active links on a webpage?
Q13. Explain your framework and how to manage data?

API/Backend
Q1. Different error codes handled? Difference b/w 401 and 403?
Q2. Difference b/w put and patch, different crud operations?

Rest Assured
Q1. Different types of Authentication? Which type of Api you are using?
Q2. How to handle Oauth 2.0 in RestAssured?
Q3. What is POJO, serialization and de-serialization?
Q4. How to traverse to particular element in json response?

Jenkins
Q1. How to configure project in Jenkins?
Q2. How occasinally your build is run and different trigger scenarios like as soon as the dev build comes or nightly execution?

Maven
Q1. Lifecycle of Maven?
Q2. What is dependency, group id and artifact id?

GIT
Q1. How to commit and push code?
Q2. How to resolve conflict?

TestNG
Q1. What is TestNG.xml, difference b/w @BeforeTest and @BeforeMethod?
Q2. How to generate testng.xml dynamically and format of TestNG.xml?
Q3. How to do set priority, exclude the test cases, different annotations, how to run test cases in parallel?
Sevaral Companies mostly Mnc’s, Gurgaon. Ghaziabad, India   Yes
Selenium, API/BackEnd, Rest Assured, Maven, TestNG, Cucumber Selenium WebDriver
1.How to read data from pie chart tool tip values from a website using Selenium WebDriver
2. Verify those values (from question 1) with response body in postman
3. How to launch chrome browser with specific chrome extensions


Maven
1. What are transitive dependencies.
2. I have one dependency say ‘Z’ with some version and it has its transitive dependency say ‘A’ with some version  in Effective POM. Now if , i add ‘A’ dependency explicity with other version in the POM.xml ,then from which dependency of ‘A’ will be considered by Maven .
If u want to exclude a dependency how will you do?
3. How to validate whether a particular jar is added properly or not in Maven
4. What is a snapshot version
5. How to create your own jar file and publish others with your logics
6. What exactly maven-sure file plug in does

TestNG
1. How to run only 50 test cases out of 100 test cases with out using method level annotation i.e @Test(enabled=true)
2. Asked me to draw Hierarchy of a testng.xml file
Dell Secure Works, Hyderabad Hyderabad 1.
I explained answer for first question this way
//locate tooltip pie chart in the DOM
  WebElement toolTip = driver.findElement(By.xpath(“//div[contains(@id,’_tooltip’)]”));

//locate webelement of color for which u want to get the tool tip value
WebElement GreenColor = driver.findElement(By.xpath(“xxx’)][@fill=’#295454′]”));
GreenColor.click();
  System.out.println(ToolTip.getText());

He is bit impressed but i am not sure with that approach

2.I don’t know answer for the second question

3. Explained answer this way
https://seleniumjava.com/2016/05/22/start-the-chrome-browser-with-extensions/

***************************************
Maven Questions

1. I answered Transitive dependencies question
2. For this i said we can use tag and what ever the dependency we declared in POM.xml that one will override the transitive dependency. Interviewer bit convinced but digged deep into that asking how
3. I said “mvn dependency:analyze” would do but he asked what exception it throws if a particular class is not imported from a Jar and 
I said from exception it thrown,  i will verify but he said there is a way to check whether jar added succesfully or not
4. A snapshot version in Maven is one that has not been released yet

***************************************
Yes
Selenium How to automate google calendar both online n offline  L and T  Chennai , India   No
Selenium How to write functional test cases for password field of a form in selenium which takes password in a valid format Tavant,Bangalore Bangalore,India   No
Selenium, TestNG How to retrieve dropdown values by using list? IBM india pvt ltd, chennai Chennai india   Yes
Selenium In Irctc site, I searched for trains. Let say from Bangalore to Mysore, many trains got listed. I have to track the element “Check Availability” button for  train named “Tipu sultan express”. Position of this train is not fixed in the listed train, It can appear at first or 3rd or 5th number as we change our filters to filter the trains.
So how to track that button.
Sapient Bangalore, India   No
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber Q1. How do you execute a) Feature files, b) Scenarios in parallel in BDD Cucumber? Q2. How do you pass the feature/scenario name, mentioned in some excel file, to the TestRunner file in run time in BDD Cucumber? Q3. What is the difference between Continuous Delivery and Continuous Deployment? CTS, Kolkata Kolkata, West Bengal   No
Selenium, Jenkins, Maven, TestNG, Cucumber Which base line  annotations execution sequence  are defined in testng Start UP Bangalore Testngxml tags sequence Maybe
Selenium 1-How do u handle a dynamic dropdownlist?
2-You have an automated application, today a new feature has come up and you have to test it without touching  the existing code, no changes, no addition to existing code ?
Cenduit, IQVIA Bengaluru,India 1-Handle using select class and go for visible text, the interviewer said the  answer was incorrect.
2- I was unable to answer it .
No
Selenium If an array is there and you have say more than 2 lakh records in that, lets say items  from a DC, I want to get details of a specific item, how to do that?You should not use looping or iterating. Sabre ,Bangalore Bengaluru, India Unable to anwser No
Selenium, Jenkins, Maven, TestNG, Cucumber Why do we get NoSuchSessionException in cucumber when we quit the bowser and lauch again browser using hooks @before @after Startup Bangalore Not answered, I have faced  this issue  in practically, and could not reslove  Maybe
Selenium, Jenkins, Maven, TestNG, Cucumber Extent report failed test cases will appear in skipped when we apply retry logic how to move those in failed list [eg:  failed test cases ran 5 times in reatry logic in that first 4 times test case count will come under skipped in extent report, last 5th count will come under either failed or passed based in the result] Startup Bangalore Did not answer Maybe
Selenium, Jenkins, Maven, TestNG, Cucumber What is background in cucumber Start ups Bangalore Yes Yes
Selenium Difference between page object and page factory Macy’s USA   Yes
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber Which automation framework framework you used and why? Accenture PUNE   Yes
Not Listed here I face difficulty in spotting defects in e-commerce website. I went for 2 Interviews and in both interview i was asked to find defects in e-commerce website. It’s difficult to find defects just by looking at the website. Only website url was given and was asked to point out defects and write it in excel sheet. Can you elaborate the ways to find defect…. Please Naveen do discuss this One..

Website url given in recent Interview : https://fiberbasket-dev.armentum.co/
CrushIT, Bangalore Mumbai I made a defect report template in excels and pointed out a few icon mis-alignment issue in the website. That’s it. No
Selenium, TestNG Parallel execution is possible in TestNG I forgot the company name. Bangalore, India Add thread count in suit HTML tag in TestNG XML file  No
Selenium, API/BackEnd, Postman, Jenkins, Maven, GIT/Bitbucket, TestNG, Cucumber, Not Listed here Goomo IQs
1st Round – Written Test
Set A 30 mins
1) Automate Login page w.r.t Appium/Selenium with Java as a language and mention all the tools, libraries, type of framework used
2) Automate Login API with Java as a language and mention all the tools,libraries, type of framework used
URLs, Credentials, HTML DOM  Structure, and API URL was provided

Set B 30 mins
1) Print all the Palindrome Word in a sentence and thier count
2) Print the few int values in an array, verify each no., Whether they are odd, even, prime, odd and prime, even and prime

2nd round
1) Explain complete Framework with folder structure and explain all the tools and for what reason you have used and explain all the classes in your framework
2) overloading vs overriding and where you have come across in Webdriver
3) How to handle alert popups
4) Write a TestScript for any E-commerce scenario after logging into the application
5) Exceptions you have come across and what reason they have come and how to overcome them
6) Frames handling
7) Did you work in API Manual and Automation and Appium

3rd Round
1) Automating Paginations in E-comm app, navigating from 1 to 2 and till 5 and here select a Nokia product
2) Handling frames in details like, in Frame 1, shifting one child frame to another child frame and then shifting to frame 2 etc..

4th round
1) How to Handle dynamic elements partially dynamic and fully dynamic
2) Why Hybrid Framework, what the de-merits with other kind of Frameworks
3) Explain complete hybrid framework in detail writing on a board
4) In your career, which is the best 2 months and why?
5) What test cases you Automate
6) Assume there is project which have not been tested(Manually not tested) yet,and how do you approach Automating it and it needs to be completed in 15 days,
I asked whether it’s a long term project, and does it has QA environment set up? Interviewer said yes for both.
7) Two lifts are there, I am in 2 Nd floor, Now write a Java program, so that any one of the lift which is near by should come when we press Up button
8) what are the reasons that sometimes, a Testcase will work fine for 1 browser and fails for other browsers, and how do you handle it..
9) Explain Selenium Grid
9) There are 5 medicines, a,b,c,d,e and few are Out of Expiry date and few have Expiry. The ones that have Expiry weights 500 GM, the one which completed Expiry date weighs 490 gms, in one chance(in one shot ) how to decide, which are rotten and which ones are not
11) How do you select the Framework

For Leads
1) How do you assign the task
2) How much % of work you do as a lead
3) Client interactions
4) Documents you need to prepare as a lead
5) what are the help you have provided to your team
6) What exactly is your Role
7) How much percentage of Test scripts must pass on daily basis
8) Why Test script will fail
9) Explain Selenium Grid and what are the Systems and OS you have Automated, write code

Mphasis Interview Questions
1st round
1) complete framework explaination and it’s tools
2) framework code for login
3) code to read data from Excel and that should get sent to UI i.e., for un, PW fields
4) String a= “I Love Java”
O/p Java Love I
5) String a= “I Love Java”
O/p avaJ evoL I
6) String a = “abc-2019”
O/p
[abc]
[2019]
7) Practical usage of StringBuffer

2nd round
1) String name = “Madhu”;
name.toUpperCase();
Syso(“name”);
O/P?
2) Explain TestNG in detail
3) key= fruit, value = “apple”;
key= fruit, value = “mango”;
Using any Collection how to print the values
4) There are @Test1 and @Test2 methods in TestNG, but there are methods in Test1 which gets executed only if Test2 gets executed..So how to approach?
5) How to rerun failed TestCases?
6) Explain how do you approach Testing process if you are in day 1 of the sprint
7) Explain which priority Test Suites you run in Automation,i.e., do you run all P1,P2,P3 siutes
8) Explain the priorities of the Locators you applied in your project, how do you decide
9) Explain Regression Testing w.r.t Manual  and Automation testing, what is the Approach
10) Explain smoke VS Sanity in detail
11) throw Vs throws
12) finally importance
13) what is finalize
14) why final is needed
15) why Jenkins and Maven

Pure software Interview Questions for Oracle Client w.r.t Automation using Selenium Webdriver with Java
1) Explain your current project
2) Explain Framework basic approach from your project
3) How do you shift from one location to another location in UI in the same page using Webdriver
4) challenges in Scrum
5) How to handle Mouse hovering in Webdriver
6) String reverse program
7) In a Drop-down, there are several options, and I need to select INDIA, how to achieve using Webdriver
8) Explain interface, what kind of methods it contains
9) Explain Method overriding
10) Explain Polymorphism
11) How did you extract data in your framework
12) What is Xpath and explain what situations you use Xpath and type of xpath commonly used in your framework
13) findElement Vs findElements
14) How do you handle Ajax calls and do you hard code the value or do you extract from somewhere

2nd round in Oracle
Oracle interview through PureSoftware

1) Explain your present project
2) Explain 5 scenarios for a lift
3) Explain complete Scrum process in your project
4) SQL joins related queries
5) Explain what you know about API Testing

3rd round in Oracle
Oracle interview through PureSoftware

1) Best sorting approach
2) Explain collections
3) Explain how to handle drop-downs
4) What is prequsites in postman


Global foundries Interview Questions
1) Introduce yourself
2) Program to validate your name is Palindrome or not
3) Bug life cycle in detail
4) shortfalls of Scrum
5) Extracting Authentication UN and PW from property files is a bad practice isn’t it?
6) Using Workbookfactory type for extracting data from Excel is not a good idea isn’t it?
7)Swap 2 values, int, float, double and char values without using 3rd variable
8) How to handle non reproducible issues
9) How will you execute Testcases in Jira
10) Explain complete flow of framework
11) which is better CSS or Xpath
12) how do you handle dynamic webelements
13) Explain all Test case design techniques used with an example for that Test case you have applied the respective techniques
14) Explain Bug Life Cycle in detail w.r.t any of the project you have worked
15) how to approach a deferred defect, deferred defect means it’s accepted by Dev or rejected?
Goomo, Global Foundry, Mphasis, PureSoftware BENGALURU   Maybe
API/BackEnd Suppose you have a system, and System have different types of users, A specific type user has right to create a file . How will create the test cases for API testing. Forgot the Company Name Bangalore, India API which is creating a file for a specific user for that API should be Authenticated for specific user so pass that user login detail in header of  that API and we have to test with other also. No
Selenium Are you aware of Singleton pattern? Where have you used it in your project? What are different types of exceptions in java? How to take care of dependencies in client system if a firewall is in place blocking download of dependencies? How to overcome stale element exception? How to handle dynamic web tables in selenium? How can the properties of ChromeDriver() be accessed if the driver is instantiated as WebDriver driver = new ChromeDriver()? Cognizant, Kolkata Kolkata, India   Maybe
Selenium, TestNG 1. Which locator is best to use …?
2. Different types of annotations in TestNG
3. Different types of waits used in selenium
4. How to create a xpath ? Difference between absolute and relative.
5. How to handle dynamic xpath..?
Infosys Limited, Chandigarh Chandigarh, India   Yes
Selenium, API/BackEnd, Postman, Performance Testing, Jenkins, GIT/Bitbucket Explain about Jenkin and how actually you the test cases in Jenkins. Amnet digital Hyderabad I didn’t answered  No
Not Listed here Write a program to count no of characters in a string a = (aaadddbbgdccfwsf) Visa , Bengaluru  Bangalore Wrote the program , but it was having some error in output No
API/BackEnd, Not Listed here 1) Lets say you are testing a service and you make a post call and then the service goes down .. now you want to debug what caused your service to go down so what will be your debugging steps

2) what are the different exceptions you have seen in UI and Backend ? And then how do you debug that?

3) What are the different reasons a service can go down

4) When there is out of memory exception then what would be your next step and then how do you find that what caused it out of memory

5) How would you change the nested part of the JSON in API Automation

6) How do you handle a flash which comes up in the website in between like it is a flash file. How do you check whether it is a flash or not a flash in selenium

7) How do you decide whether it is a frontend bug or a backend bug.. what things do you check so that you know it.
Amazon Bengaluru   No
Selenium, Jenkins, Maven, TestNG, Cucumber How Do you retry failed test cases
How do you run test cases parallel
What are testNG annotations serial order
What is polymorphism
LTI Mumbai   No
Selenium, Appium, Postman, JMeter, Performance Testing, Jenkins, GIT/Bitbucket, TestNG, Cucumber What is toska suite…? Waves pvt LTD pune Pune I don’t know related on that in my project i can not be used No
Selenium, Maven, TestNG, Not Listed here how do you validate sort table in the angular application using protractor  virtusa chennai chennai,India    Maybe
Selenium, Jenkins, Maven, TestNG 1. How do you start writing your test cases in automation?
2. Explain the execution flow?
Optum, Hyderabad Hyderabad, India 1. After getting requirements in the form of user story, we start writing the tests in eclipse No
Selenium, API/BackEnd, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, TestNG Need java questions for Selenium java  Cognizant technology  Chennai    No
Selenium Where we have applied opps concepts in automation framework. Teranet, Trivandrum, kerala, india Trivandrum, kerala, India Iam able to explain some of the opps concepts like abstraction, encapsulation etc but I couldn’t explain about polymorphism and interface Maybe
Selenium How do you choose test data for automation
How do you pick user stories or test cases for automation, What kind of test cases you won’t pick to automate

How do you give estimations? Based on what you give estimation in Agile?(like Planning poker method etc)
CGI Edinburgh Edinburgh, Scotland   Maybe
JMeter, Performance Testing how to generate 1000 of threads using only one thread? capgemini Hyderabad you have clear Maybe
Selenium, Jenkins, Maven, GIT/Bitbucket, TestNG Maven Life Cycle  Accenture Mumbai, India Didnt remember Yes
TestNG 1) 10 test case are there B, C, A etc etc  and I want to run in the same order without using priority, depends on etc. What does your testname starts like in testng? ajio Bangalore   No
Not Listed here I was asked to solve this https://gist.github.com/MMore/dc09c01f62a65f6886f440baa0e549c7 FRIDAY Bangalore I have used regex and solved it in my way still they rejected. So I am curious to know how it could be done differently No
TestNG 1) 10 test case are there B, C, A etc etc  and I want to run in the same order without using priority, depends on etc. What does your testname starts like in testng? ajio Bangalore   No
Rest Assured What is the difference between error response 4xx and 5xx? ImpactQA, Noida Greater Noida, India   No
Selenium, API/BackEnd, Appium, Rest Assured, Postman, JMeter, Performance Testing, Jenkins, Maven, GIT/Bitbucket, WebDriverIO, TestNG, Cucumber How to find all pairs on integer array whose sum is equal to given number Amazon Karimnagar, Telangana   No
Selenium how to compare dynamically generated item prices on amazon website healthcare client Karimnagar India wait until element is present explicit wait Maybe
Selenium How to upload  the latest file which is having  name based on date and time stamp of file creation. In this case we never know the filename before hand and there could be multiple files in the directory. Ex- File name- 18042020102000.jpg. Here file was created on 18th April 2020 at 10:20:00 am.

Microsoft GHAZIABAD My Answer – Get the name of all the files in list and than arrange the list in decending order, pick-up the first entry from the list.
However the interviewer was not very convinced by this answer.
No
Jenkins How to pass the values (Parameters) from Jenkins to Selenium suite.
If we need to configure the test environment in Jenkins and from Jenkins we need to control on which test environment the suite should be triggered.
Cigniti GHAZIABAD By creating the parameterized build in Jenkins and reading the parameter in Maven POM. Passing parameters of Maven POM to selenium script. Yes
Selenium, TestNG If set does not maintain any order then how window handles function will move the focus in an orderly manner to parent to child window Bnp Paribas- mumbai  PUNE   No
Selenium, TestNG How can you take screenshot of a particular element in selenium Neosoft -mumbai  PUNE   No
Selenium, TestNG How can you move from frame F1 to F2 in a webpage and then click the submit button below the frames Morning star – vashi PUNE   No
Selenium, API/BackEnd, TestNG How to handle and test conccurrent calls and how to handle DB locking ? How to test asycncronus calls ? Mention the area where we cannot use explicit wait ?  Netsol, Lahore Lahore, Pakistan   Maybe
Selenium Test data generation question. Given only 3 alphabets as input. Script will find total possible strings. Write all possible test data for this. Can you pls help in solving these type of questions sir Amazon,India Chennai,India   No
Selenium, Jenkins, GIT/Bitbucket Selenium(type of waits,handling window pop up,keyboard events,xpaths,reports);integration with git and jenkins Pune-Capgemini,hcl Pune,India   Yes
Selenium Read the data of 2 columns and write in 3rd column in excel sheet using selenium. Capgemini-Pune India Pune I have written the code for that but don’t know that was correct or not. Yes
Selenium 1. SOLID Design Principles – Code with real-time implementation in your project.
2. Interfaces- Real-time implementation in your framework?
3. Difference between Interfaces and Abstract class?
4. Generics in C#?
5. Test Cases to test Google Search Page.
Verizon Connect, Dublin Dublin, Ireland   Yes
Not Listed here E2E Test case for adding credit card to customer account.

E2E Test cases for Making transmission with credit card at any site.

How do you Test the features where based on given zip code it calculates the delivery charges. Does it calcuting amount correct or not.

How do you debug when one of customer says, web app not working from my side. Not able to click options (Other than cookie, java script options settings on browser, Browser used, OS) 
Slk  Hyderabad   Maybe
API/BackEnd The QA director asked me this question – When your Dev counter parts are using Spring Boot, Hibernate, etc. as their technical stack, then why can’t you use the same stack for developing your automation framework? Why can’t you just move away from Core Java? VuClip, Pune Pune I said that my automation framework is working fine with Core Java and Collections and it hardly going to make any difference switching to Spring Boot from Core Java. I later realised that I should not have answered that way. Unfortunately I couldn’t clear that round.
Facing such tricky questions from the Senior Management is sometimes really difficult.
No
Selenium I want to create property file where I want to use with single object all over the project..how it’s possible.. IBM Bengaluru   No
Selenium, Postman, JMeter, TestNG 1) what are regular expressions and how do you use in your framework?.
2) if upload type is not file in html code, then how can you proceed further to upload a file using selenium webdriver?.
3) HOW GET AND POST WORKS IN POSTMAN EXPLAIN WITH SOME REALTIME EXAMPLES?.
4) EXPLAIN RECORD AND PLAY FEATURE IN JMETER?.
5) WHAT IS THE USE OF PRIORITY IN TESTNG AND HOW DO THEY WORK?.
1) CRIMSON INTERACTIVE , MUMBAI Mumbai,India 1)i was not aware of regular expression
2) i will tell developer to pit upload type= file and then proceed.
3) did not answer
4) HTTP SCRIPT RECORDER FEATURE IN JMETER allows you to record the actions perfomed by the user on all the available web elements in the form of scripts in  JMETER background and user can switch to JMETER to stop the recording after desired actions are conpleted.
5)  AFTER SETTING PRIORITY TO THE COMPONENTS OF TEST IN TESTNG, based on  priority, the components will be executed.
Yes
Selenium How to write test case if following is the scenario :
If you are working in an insurance company and suppose tomorrow company paid some extra amount to some customer after completing their Policy for example say there would be 10 customer who has the insurance policies and after giving all the EMI i.e after completion of the policy , company pay them back .After some time company realise that they paid some extra amount to some customer ?
Now question is How would you test that which customer gets extra or how would you write test cases on this scenario?
AIA  Tarneit, melbourne Nothing No
Selenium What are the boundary cases in an multimedia app Like whatsapp? Infosys Tarneit, melbourne Nothing No
Selenium Framework used in your previous project Cognizant Bangalore   Yes
Selenium, API/BackEnd, TestNG, Cucumber Mostly Java Questions were asked:
1. Can we write a Java Program without main method?
2. Difference between abstract class and interface
3. Difference between throw and throws
4. Difference between BDD and TDD and which I would like to prefer
5. Architecture of POM
6. Can a hash map have a null key
7. Difference between GET and POST HTTP method
8. Multithreading in Java
Square Yards, Gurgaon Gurgaon   Yes
Selenium, Appium How to validate data from csv files Mid level company  Gurgaon   Maybe
Not Listed here Behavioral questions
1. Please provide us an example of an occasion when you have communicated appropriately and clearly.
2.   Please provide us an example of when you have achieved results by focusing on delivery of objectives
3. Please provide an example of successfully leading a team/Project/task or developing people
4. Please provide an example that demonstrates your commitment to delivering and excellent high quality service
5. Please provide an example of when you have used your organization skills to put plans and resources in place
Visit Scotland Edinburgh,United Kingdom   No
Not Listed here Difference between Abstract Class and Interface with examples in Java 8 Rightpoint, Genpact, Boston, MA, USA MANCHESTER   No
Selenium Scenario : You have joined my company as TeamLead , and we following agile methodology , a project is given to you , which framework you chose for automation ?How to you Kick start the Project ? Is Your automation is helpful fro Tenant or organisation  and how ? Digital Harbor Bangalore    No
Selenium, Not Listed here 1. Given array a we have to return the next small highest number to each element in the array, if there is no next small highest number return -1 Eg: Input= [5,2,1,4,7,6] output=[6,4,4,6,-1,-1]
2. Given a number we need to return a single digit by subtracting the consecutive numbers Eg: n=6234 6-2 = 4 2-3=1 (ignore -ve sign) 3-4=1 411 4-1=3 1-1=0 30=3-0=3 3 so we need to return 3
3. There are a series of pillars say n pillars. You’re standing at x distance from 1st pillar so that you can see the pillars. Given the height of each pillar, find the no of pillars you can see
4. Given a series of +ve integers of size ‘n’. whose difference of adjacent elements is 1. Find the index of first occurrence ‘k’, where k is a value in array
5.Debugging- Uploading files to Instagram. While uploading 10 images to Instagram, 3 images are displaying as blank images
Amazon, Chennai Chennai, India   Maybe
Selenium, Maven How do you set your jar files in your current project? Prime Focus Infotech Bangalore, India Currently we are using maven tool in my project so whenever we add the required dependency it automatically downloads the required jar files. No
Selenium, TestNG, Cucumber How do you handle web table and write a code snippet Suneratechnologies-Hyderabad Hyderabad I told we we can use xpath and split the xpath and can loop  Yes
Selenium How to handle right click operation of mouse ?
Static binding and dynamic binding?
Cucumber architecture?
What is POM?
Use of Auto IT?
What are the arguments in java script executor (Horizontal and vertical scroll)?
How to find child node using xpath?
How do you switch to frame ?
How do you get cell value from excel?
Diff between Map and list ?
What are the exceptions seen so far ?
How do you take screenshot for failed test cases ?
Suneratechnologies -Hyderabad Hyderabad   Yes
Selenium, API/BackEnd Extract total number of test case from given string

TestCasesPassed100TestCassesFailed50TestCasesSkipped25

Output should be 175
GlobalLogic, Noida Delhi, India Written logic using Matcher.pattern Yes
Selenium New to selenium  Hyderabad  Hyderabad    No
Selenium 1.How to locate elements if the elements have the same name,id and attributes in same tags?
2. How you make sure your automation script is testing everything in the application?
3.For test planning are we using any tools?
4.What are the challenges/difficulties faced during automation?
5. How to test database and related data using selenium?
Infosys(1,2), CTS(3),Gridpoint(4),Hexaware(5) Sterling,Virginia, USA 1.I tried answering custom xpath but it was not correct.
2. I answered like using assertions but I think he was asking me about logs
3. Not answered
No
Selenium If there is a bug in production what would you do?  N/A New York, USA   Maybe
Appium Test Test Test Test Yes
Selenium, API/BackEnd, Appium, Postman, Maven, TestNG, Cucumber Want to certifications on selected list New York  United states   Maybe
Not Listed here Consider customer asked you automate new application from scratch. What are factors considered for choosing automation tool, designing framework Capgemini Chennai India   No

Please follow and like us:

Handle DropDown using select Class in selenium

Handle DropDown using select Class in selenium

 

1. Overview

In this article, we’ll explore the select class from the org.openqa.selenium.support.ui.Select package to work on Drop-Down.

2. Type of DropDowns/DropBox/ListBox

There are generally two types of DropDowns

  1. Single select DropDown
  2. Multi-select DropDown

  • Single select DropDown when we can select only one option from the DropDown list like below:

Values to select will be displayed like this:

  • Multi-select DropDown when we can select more than one option from the DropDown list like below

3. Role of Select Class in Selenium:

  • The Select class is a WebDriver class which provides the implementation of the HTML

  • This class can be found under org.openqa.selenium.support.ui.Select package.

  • Select is an ordinary class as any other class , so its object is created by passing the WebElement to its constructor.

  • It will throw error as asking to add arguments to the command:

            Syntax : Select select = new Select(); 

So, specify the web element location using the select Element as done below:

Declaring the dropDown element as an instance of the Select class

Let’s find out what operations we can perform with the help of this Select class reference i.e. selectFromDropDownObj

 

Select Methods

As it can be seen from the above figure, we can select/deselect the values from the drop-down list based on our requirements.

Let’s explore some of the above methods to get better understanding of the same:

We can select our drop-down values with these below methods

  1. selectByIndex
  2. SelectByVisibleText
  3. selectByValue

Let’s examine the below code first:

  • selectByIndex (int index): This Function takes an index value from drop-down list and it starts from 0 for the first value and returns void.
  • selectByVisibleText(String text): This Function takes text in String format from the drop-down list and returns void.
  • selectByValue(String value): For this first inspect the element from DOM and select the value as shown below:

Note : The Most preferred way is to select by byVisibleText() because in ByIndex(),  index can be changed for dynamic drop down values but it can be used for static dropdown values like Month, Year and Date. 

Let’s explore getOptions Method:

Syntax:

List<WebElementallOptionsObj =selectFromDropDownObj.getOptions();

for(WebElement getAllOptions:allOptionsObj)
System.out.println(getAllOptions.getText());

This will print all the options contains in the DropDown and we get our Output same as below:

 

console Output

Another useful Method isMultiple:

This method tells us whether dropDown is single select or multi-select, it doesn’t accept anything and returns a boolean value.

 

isMultiple()

Now, if requirements changed that selected value needs to be deselected then we can perform below actions on the same.

  • deselectByIndex(int index) : void –Deselect the option at the given index.
  • deselectByValue(String Value): void –Deselect the matching option with given argument Value.
  • deselectByVisibleText(String Text) : void – Deselect the matching option with given argument Text.

Now, let’s jump into the second Type of DropDown i.e Multi-select:

Before that let’s take a glance at below code

 

select Multiple options

  1. In the above code , we first inspect the select element and then as usual instead of one select methods we can use more than one select methods. 
  2. One catchy method here is getFirstSelectedOption() it returns the WebElement and display which value from the dropdown is selected first by using getText.

That’s it we have mastered over the select class.

Below code for your reference and output of the same:

 

and output on the browser will be similar to :

package com.example.automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
/**
* @author Mandeep Kaur
* @Date 29 April,2020
*/
*/
*/
public class SeleniumConfig {

public static void main(String[] args) throws InterruptedException {

String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);

WebDriver driver = new ChromeDriver();
driver.get(“https://testuserautomation.github.io/DropDown/”);

//inspect over the Drop Down menu
WebElement selectCitiesObj = driver.findElement(By.xpath(“//select[@name=’Cities’]”));
Select selectFromDropDownObj = new Select(selectCitiesObj);

//select by index , index will start from 0 for first value
selectFromDropDownObj.selectByIndex(0);

//select by value, value to be found in HTML DOM
selectFromDropDownObj.selectByValue(“Texas”);

//select by Text given in the dropDownList
selectFromDropDownObj.selectByVisibleText(“CA”);

//getOptions : to get all the options from the drop-down
List allOptionsObj = selectFromDropDownObj.getOptions();

for (WebElement getAllOptions : allOptionsObj)
System.out.println(getAllOptions.getText());

//isMultiple : is it multi select drop-down if no then it returns false:
boolean isSuccess = selectFromDropDownObj.isMultiple();
System.out.println(isSuccess);

//MultiSelect DropDown
WebElement selectBillsObj = driver.findElement(By.xpath(“//select[@id=’Bill’]”));
Select selectBillFromDropDownObj = new Select(selectBillsObj);

selectBillFromDropDownObj.selectByValue(“Travel”);
System.out.println(selectBillFromDropDownObj.getFirstSelectedOption().getText());
selectBillFromDropDownObj.selectByIndex(3);
driver.close();

}
}

4.Conclusion

In this article , we have learnt about the handling of drop-down using select class in selenium.

Cheers!!

Naveen AutomationLabs

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

 

 

 

 

Please follow and like us:

Handling of Dynamic Web Table in Selenium

  1. Overview

In this article , we will learn to handle Dynamic Web Table in Selenium WebDriver .

2. Basic Concepts:

  • A table with rows and columns on a web page is called a web table. In HTML, a table is created using  tag. 
  • Table contains  headers represented as, rows asand Coloums as tag
  • There are two types of web Tables

  1. Static web table: Number of rows and columns will be static means constant that will not be changed. Here we just need to find the WebElement of the particular row or column and simply can perform operations on the cell.
  2. Dynamic table: Number of rows and columns will be dynamic. It will be kept on changing based on data and this the area where we will be focussing on.

3. Ways to Handle Dynamic WebTable:

  1. The standard way where we will iterate over the rows and columns and reach to a particular cell and get the cell value.
  2. By using custom XPath

Before proceeding further, let’s see how dynamic table looks like :

Table with checkbox , rows and coloumns

And below is the HTML representation of the above web table:

So, based on the data input we can increase or decrease our number of rows or columns.

Since we have seen what a web table is and how it is created, now let’s take the simple scenario :

1)click on checkbox where firstName is Will and remember it’s a dynamic table, hence “WILL” now on 3rd row can be shifted to other row based on the insertion or deletion of data.

  • Let’s implement it by First Method:

Let’s accomplish this task first by looking at the code snippet below

We’ll break this code into steps to get a deeper understanding of it:

Step1 : Capture xpath of the FirstName Row and observe the pattern

  • First Row xpath: //table/tbody/tr[2]/td[2] –>jessica
  • second Row xpath: //table/tbody/tr[3]/td[2] –>Ammy 
  • Third Row xpath: //table/tbody/tr[4]/td[2] –>Will and so on
  • Here can we say that our rowis getting changed and our columnis constant.

Step2: Catch before and after XPath from the point our row started changing as done in the code.

Step 3: Now, we have captured the before and after XPath.Find out the total row size by size() function of the java collections.

Step 4: Start iterating over the rows, start the row index with 2 as the first row would be reserved for headers.

Step 5:Get the text of all the rows and store it to the variable firstNames and print it to see if we are able to capture it

Step 6 : Final step of our task , that click the checkbox where FirstName is Will

For this step, we put one condition that if firstNames contains WILL then only checkbox has to be clicked. if it exists it will click the checkbox prior to WILL.

Since WILL is existing in the table , it will click the checkbox and we can capture it from the browser:

and our output on the console is similiar to following :

  • By Second Method : with Custom XPath

We can achieve our task with single statement :

 driver.findElement(By.xpath(“//td[contains(text(),’Will’)]//preceding-sibling::td//input[@type=’checkbox’]”)).click();

yes , that ‘it , below code for your reference

Let’s try to understand this method :

firstly visit over XPath_Axes , here you will get to know how to traverse from one node to another node.

Next, in the above we have spied over FirstName with text Will and we found out Will Sibling is td when we proceed upwards and then we get our input as a checkbox and from here we can simply capture it.

4. Which Method to choose

As can be conveyed from the above methods, the custom method is the best way to handle web dynamic table :

Reasons :

  1. In the First Method, it’s a lengthy method whereas the second method is just a single line statement
  2. In the first Method, we had to use for loop with conditions and then selecting the value, on the other hand, we need not have to use for loop
  3. As we are iterating through till all the rows it makes code slower in the first Method considering the other method can be seen fast, dynamic and efficient

Code Snippet with both methods :

package com.example.automation;
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;
/**
@author Mandeep Kaur
@Date 28 April,2020
*/
public class SeleniumConfig {
public static void main(String[] args) {
String path = System.getProperty("user.dir"); System.setProperty("webdriver.chrome.silentOutput", "true"); System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
WebDriver driver = new ChromeDriver(); driver.get("https://testuserautomation.github.io/WebTable/");
// Method 1
String before_xpath = "//table/tbody/tr["; String after_xpath = "]/td[2]";
List rows = driver.findElements(By.xpath("//table/tbody/tr"));
int rowSize = rows.size();
System.out.println(rowSize);
for (int i = 2; i <= rowSize; i++) {
String firstNames = driver.findElement(By.xpath(before_xpath + i + after_xpath)).getText();
System.out.println(firstNames);
// Now click the checkBox where first Name would be Will
if (firstNames.contains("Will")) {
// click the checkBox
driver.findElement(By.xpath("//tbody/tr[" + i + "]/td[1]/input")).click(); System.out.println("candidate has been selected");
break;
}
}
// Method 2 : By custom xpath:
driver.findElement(By.xpath("//td[contains(text(),'Will')]//preceding-sibling::td//input[@type='checkbox']")) .click();
driver.close();
}
}

5. Conclusion

In this article , we learnt about how to handle dynamic Web Tables.


Cheers!!

Naveen AutomationLabs

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeep-kaur-486ba9106
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

 

 

 

 

Please follow and like us:

Selenium WebDriver -Navigation Commands

1.Overview  

In this short article, we’ll be focusing on various Navigation commands that allow the browser to move forwards, backwards in the browser’s history.

2.Difference Between the driver.get(“url”) and driver.navigate().to(“url”);

On the basis of Method Calls:

driver.get() used to launch a particular website, it doesn’t maintain the browser History and cookies so, we can’t use forward and backward button whereas driver.navigate().to() is also used to launch the particular website but it maintains the browser history and cookies, so we can use forward and backward button to navigate between the pages during test case writing

On the grounds of page Load Time:

driver.get() wait till page gets loaded and perform actions thereafter ,considering  driver.navigate().to() does not wait for page load.

On account of Server API Calls:

driver.get() method internally sends HTTP GET request to Selenium Server Standalone. On the contrary driver.navigate().to method sends HTTP POST request to Selenium Server Standalone.

GET /session/:sessionId/url Retrieve the URL of the current page.
POST /session/:sessionId/url Navigate to a new URL.

On the grounds of page Load Time:

driver.get() is slow as it waits until the page is loaded.

driver.navigate().to() – faster as it does not wait for page to be loaded

3. Method Explanation

Now, to access the navigation methods, just type driver.navigate(). like below:

Let’s try to understand these methods in detail:

  1. Navigate To Command – driver.navigate().to(“url”)

There are two ways to define this method:

This method Loads a new web page in the current browser window. It accepts a String parameter and returns void.

This method accepts URL class instance by importing package import java.net.URL; and returns void.

2)     Forward Command – driver.navigate().forward();

This method enables the web browser to click on the forward button in the existing browser window, it takes you forward by one page on the browser’s history.  It neither accepts nor returns anything.

3) Back Commanddriver.navigate().back();

This method enables the web browser to click on the back button in the existing browser window. it takes you backwards by one page on the browser’s history. It neither accepts nor returns anything.

4)  Refresh Command- driver.navigate().refresh();

     This method refreshes the current page. It neither accepts nor returns anything.

 

Let’s look at this function in more details with below code snippet:

Upon executing the above code, we will get the output on console similar to:

Now many of us would be wondering why this exception occurs?

Let’s break down our answer to get a deeper understanding:

  • When WebDriver executes the above code then it assigns an internal id  to every WebElement and it refers this id to interact with that element and now we are refreshing our web Brower with driver.navigate().refresh();

  • It refreshes the entire page due to which the section of the DOM also gets refreshed and so is the element. In this scenario the internal id(something like “id =725541f2-6c3b-4a31-acd5-7c14ef0f8f97” as shown in below snapshot ) which WebDriver was using has become stale(old), so now for every operation on this WebElement, we will get StaleElementReferenceException .

To overcome this problem, the most recommended way is to reinitialize the element again and this time WebDriver will assign a different Id to this element, and example for this has been done for you below :

Let’s see complete code with all the navigate operations together:

package com.example.automation;

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

/**
*
@author Mandeep Kaur
*
@Date 23 April,2020
*/

public class SeleniumConfig {
public static void main(String[] args) {

String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);
WebDriver driver = new ChromeDriver();

//Navigate to the google
driver.navigate().to(“https://www.google.com/”);

//Navigate to the yahoo
driver.navigate().to(“https://in.yahoo.com/?p=us”);

//Navigate back to google
driver.navigate().back();

//Navigate back to yahoo
driver.navigate().forward();

//Navigate to the instagram
driver.navigate().to(“https://www.facebook.com/”);

//Refresh the page
driver.navigate().refresh();

//close the driver
driver.close();
}

}

4. Conclusion

In this article, we learnt about various selenium navigation commands.

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeep-kaur-486ba9106
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

Please follow and like us:
« Older posts