package practiceTestCases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FindAllLinks {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://facebook.com/");
java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println(links.size());
for (int i = 1; i<=links.size(); i=i+1)
{
System.out.println(links.get(i).getText());
}
}
}
The same way you can easily be able to find any type of WebElements on a WebPage:
Find total number of Checkboxes on a Webpage :
java.util.List<WebElement> checkboxes =
driver.findElements(By.xpath("//input[@type='checkbox']"));
System.out.println(checkboxes.size());
Find total number of Menus on a Webpage :
2
3
|
java.util.List;WebElement> dropdown = driver.findElements(By.tagName("select"));
System.out.println(dropdown.size());
|
Find total number of TextBoxes on a Webpage :
java.util.List;WebElement>
textboxes = driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
System.out.println(textboxes.size());
|
************************------------------******************
23- What is Page Load Timeout?
Ans-When automation script run on the browser. Sometimes scripts are faster than the web application that
time scripts looking for an element but it can’t be found because the web page not loaded completely
and throws an element not found or element not visible exception. To eliminate these kind of
exception and ensuring script run smoothly for this we mention or set page load time out.
Ex: driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
************************------------------******************
24- Can you explain implicit wait, explicit wait and fluent wait and what is the difference between
all of them? Which one you have used frequently?
Ans- Implicit Wait
Selenium WebDriver has borrowed the idea of implicit waits from Watir. This means that we can tell
Selenium that we would like it to wait for a certain amount of time before throwing an exception that it
cannot find the element on the page. We should note that implicit waits will be in place for the entire time
the browser is open. This means that any search for elements on the page could take the time the implicit
wait is set for.
Ex: WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
Fluent Wait
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.
Ex: // Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
Explicit Wait
It is more extendible in the means that you can set it up to wait for any condition you might like.
Usually, you can use some of the prebuilt ExpectedConditions to wait for elements to become clickable,
visible, invisible, etc.
Ex:
2
3
|
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
|
Difference Between Implicit, Explicit and Fluent Wait
Implicit Wait: During Implicit wait if the Web Driver cannot find it immediately because of its availability,
the WebDriver will wait for mentioned time and it will not try to find the element again during the specified
time period. Once the specified time is over, it will try to search the element once again the last time before throwing exception. The default setting is zero. Once we set a time, the Web Driver waits for the period of the WebDriver object instance.
Explicit Wait: There can be instance when a particular element takes more than a minute to load.
In that case you definitely not like to set a huge time to Implicit wait, as if you do this your browser
will be going to wait for the same time for every element.
To avoid that situation, you can simply put a separate time on the required element only.
By following this your browser implicit wait time would be short for every element and it would be large
for specific element.
Fluent Wait: Let’s say you have an element which sometime appears in just 1 second and some time it
takes minutes to appear. In that case it is better to use fluent wait, as this will try to find element again and
again until it finds it or until the final timer runs out.
************************------------------******************
25- What is JavaScript Executor and where you have used JavaScript executor?
Ans- JavascriptExecutor it is an interface. It Indicates that a driver can execute JavaScript, providing
access to the mechanism to do so.
There were lots of scenarios’ their we need java-script should be executing for some element that are
as follows:
1. when element is not clickable using locators then we can have used JavaScript.
2. While working with frames we used JavaScript.
3. The most recently while working with ck-editor I used JavaScript executers.
4. For the bootstrap calendar when the conditions for using selenium command it can’t be possible that
time I used JavaScript executer etc.
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Examples: 1. How to generate Alert Pop window in selenium?
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world');");
************************------------------******************
26- How to capture Screenshot in Selenium? Can we capture screenshot only when test fails?
Ans- For taking screenshots Selenium has provided TakesScreenShot interface in this interface you can
use getScreenshotAs method which will capture the entire screenshot in form of file then using FileUtils
we can copy screenshots from one location to another location.
Ex: // Take screenshot and store as a file format
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("C:/selenium/error.png"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
And we can capture screen-shot while test fails we can do this by following way.
Ex: create one method for capturing screen-shot. And then call this method in test methods catch block.
public static void captureScreenShot(WebDriver ldriver){
// Take screenshot and store as a file format
File src= ((TakesScreenshot)ldriver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile method
FileUtils.copyFile(src, new File("C:/selenium/"+System.currentTimeMillis()+".png"));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
Now call this method in test methods catch block.
************************------------------******************
27- What is Web Driver Listener and Usage of the same?
Ans- In general, terms, Listeners are whom that listen to you. If you talk about Webdriver Listener so you
should make a note of some classes and interfaces.
1- WebDriverEventListener – This is an interface, which have some predefined methods so we will
implement all of these methods.
2-EventFiringWebDriver- This is an class that actually fire Webdriver event.
Why we are using Webdriver Listeners:If you talk about Webdriver we are doing some activity like type,
click, navigate etc this is all your events which you are performing on your script so we should have
activity which actually will keep track of it. Take an example if you perform click then what should happen
before click and after click. To capture these events, we will add listener that will perform this task for us.
Ex: package listerDemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;
public class ActivityCapture implements WebDriverEventListener {
@Override
public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {
}
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
System.out.println("After click "+arg0.toString());
}
@Override
public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("After FindBy "+arg0.toString());
}
@Override
public void afterNavigateBack(WebDriver arg0) {
System.out.println("After navigating back "+arg0.toString());
}
@Override
public void afterNavigateForward(WebDriver arg0) {
System.out.println("After navigating forword "+arg0.toString());
}
@Override
public void afterNavigateTo(String arg0, WebDriver arg1) {
System.out.println("After navigating "+arg0.toString());
System.out.println("After navigating "+arg1.toString());
}
@Override
public void afterScript(String arg0, WebDriver arg1) {
}
@Override
public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {
}
@Override
public void beforeClickOn(WebElement arg0, WebDriver arg1) {
System.out.println("before click "+arg0.toString());
}
@Override
public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {
System.out.println("before FindBY "+arg0.toString());
}
@Override
public void beforeNavigateBack(WebDriver arg0) {
System.out.println("Before navigating back "+arg0.toString());
}
@Override
public void beforeNavigateForward(WebDriver arg0) {
System.out.println("Before navigating Forword "+arg0.toString());
}
@Override
public void beforeNavigateTo(String arg0, WebDriver arg1) {
System.out.println("Before navigating "+arg0.toString());
System.out.println("Before navigating "+arg1.toString());
}
@Override
public void beforeScript(String arg0, WebDriver arg1) {
}
@Override
public void onException(Throwable arg0, WebDriver arg1) {
System.out.println("Testcase done"+arg0.toString());
System.out.println("Testcase done"+arg1.toString());
}
}
Let’s Discuss one of these methods
@Override public void afterClickOn(WebElement arg0, WebDriver arg1) {
System.out.println(“After click “+arg0.toString());
}
In above method we are simply printing on console and this method will automatically called once click
events done. In same way you have to implement on methods.
Note- We generally use Listener to generate log events
Step 2- Now create your simple script, create EventFiringWebDriver object, and pass your driver object.
EventFiringWebDriver event1=new EventFiringWebDriver(driver);
Step 3- Create an object of the class who has implemented all the method of WebDriverEventListener so
in our case ActivityCapture is a class who has implemented the same.
ActivityCapture handle=new ActivityCapture();
Step 4- Now register that event using register method and pass the object of ActivityCapture class
event1.register(handle);
************************------------------******************
28-How to scroll in Selenium Webdriver?
Ans-Selenium support auto scroll to find an element but sometimes we need to scroll based on requirement like scroll up and down. We can perform this using Java Script. In this video, we will discuss How to Scroll page up and down in Selenium Webdriver.
ex: WebDriver driver =newFirefoxDriver();
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)","");
************************------------------******************
29- Can you write login script for Gmail or any other application?
Ans-Yes.
************************------------------******************
30- How to upload files in Selenium? Have you ever used AutoIT?
Ans-We can upload file in web application by using directly sending path in sendKeys. But at sometimes
selenium path could not accept or upload the things, for this we used AutoIT tool.
1-AutoIt is freeware automation tool that can work with desktop application too.
2-It uses a combination of keystrokes, mouse movement and window/control manipulation in order
to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys).
************************------------------******************
31- How to handle untrusted Certificate in Selenium?
Ans- Untrusted SSL certificates: Whenever We try to access HTTPS website so many time so will face
untrusted SSL certificate issue. This issue comes in all browser like IE, Chrome,Safari, Firefox etc.
This certificate some in multiple conditions and we should know all of them so that we can rectify
them easily.
1- Each secure site has Certificate so it certificate is not valid up-to date. 2– Certificate has been expired on date 3– Certificate is only valid for (site name) 4- The certificate is not trusted because the issuer certificate is unknown due to many reason.
Handle untrusted certificate in selenium.
Step 1-We have to create FirefoxProfile in Selenium. Step 2- We have some predefined method in
Selenium called setAcceptUntrustedCertificates() which accept Boolean values(true/false)-
so we will make it true. Step 3-Open Firefox browser with above created profile.
Handle untrusted certificate in Firefox
public class SSLCertificate {
public static void main(String[] args) {
//It create firefox profile
FirefoxProfile profile=new FirefoxProfile();
// This will set the true value
profile.setAcceptUntrustedCertificates(true);
// This will open firefox browser using above created profile
WebDriver driver=new FirefoxDriver();
driver.get("pass the url as per your requirement");
}
}
Handle untrusted certificate in Chrome
// Create object of DesiredCapabilities class
DesiredCapabilities cap=DesiredCapabilities.chrome();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.chrome.driver","Chrome driver path");
// Open browser with capability
WebDriver driver=new ChromeDriver(cap);
Handle untrusted certificate in IE
// Create object of DesiredCapabilities class
DesiredCapabilities cap=DesiredCapabilities.internetExplorer();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.ie.driver","IE driver path");
// Open browser with capability
WebDriver driver=newInternetExplorerDriver(cap);
Handle untrusted certificate in Safari
// Create object of DesiredCapabilities class
DesiredCapabilities cap=DesiredCapabilities.safari();
// Set ACCEPT_SSL_CERTS variable to true
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Set the driver path
System.setProperty("webdriver.safari.driver","Safari driver path");
// Open browser with capability
WebDriver driver=new SafariDriver();
************************------------------******************
32- How to handle window authentication window in Selenium Webdriver?
Ans- Each company having some proxy setting for specific application so while running script using
Selenium you will get this authentication window which ask for Username and password so until
we don’t handle this you cannot navigate to parent window.
There are two ways to handle this issue.
1. Handle windows authentication using selenium Webdriver. You can provide credentials in URL
itself it means we will add username and password in URL so while running script it will bypass
the same.
2. We can use AutoIT to handle these kind of windows authentication.
We can use AutoIT again to handle this authentication window for this Please check whether
you have AutoIT installed or not. 1) Open the Url ENGPROD on which the authentication is required and open the AutoIt Window Info tool to get the name of the class and the text of the authentication window.
************************------------------******************
33- What is Firefox Profile?Ans: Firefox Profile
Firefox saves your personal information such as bookmarks, passwords, and user preferences in a set of files called your profile, which is stored in a separate location from the Firefox program files. You can have multiple Firefox profiles, each containing a separate set of user information. The Profile Managerallows you to create, remove, rename, and switch profiles.
Need of New Firefox Profile
The default Firefox profile is not very automation friendly. When you want to run automation
reliably on a Firefox browser it is advisable to make a separate profile. Automation profile should be
light to load and have special proxy and other settings to run good test.
You should be consistent with the profile you use on all development and test execution machines.
If you used different profiles everywhere, the SSL certificates you accepted or the plug-ins you
installed would be different and that would make the tests behave differently on the machines.
· - There are several times when you need something special in your profile to make test
execution reliable. The most common example is a SSL certificate settings or browser
plug-ins that handles self-signed certs. It makes a lot of sense to create a profile that
handles these special test needs and packaging and deploying it along with the test execution
code.
· - You should use a very lightweight profile with just the settings and plug-ins you need for the execution. Each time Selenium starts a new session driving a Firefox instance, it copies the entire profile in some temporary directory and if the profile is big, it makes it, not only slow but unreliable as well.
Steps to create new profile in Firefox:
1. Close Firefox browser if open.
2. Run -> firefox.exe -p
3. It opens Firefox user profile window.
4. Create new profile by clicking create profile and follow the steps.
You can use this in your scripts by using following code:
Code:
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile. getProfile("profileToolsQA");
WebDriver driver = new FirefoxDriver(myprofile);
***********************-------------------********************
34- What are the issues or Challenges you faced while working with IE Browser?
Ans- Challenges with IE browser in selenium Webdriver.
ü Openqa.selenium.NoSuchWindowException. (This is a common issue with Selenium and you can
avoid this by doing some IE setting, which we are going to discuss now.)
ü sendKeys works very slow it takes 1 to 2 seconds to type each character.
(This is a known issue with Selenium and it only happens once you work with IE 64 bit driver.)
Solution:You can download IE Driver 32 bit and start using it, even you are working with 64 bit OS this 32 bit IE driver works every time.
ü Unexpected error while launching Internet Explorer.Protected mode must be set to the same value.( When I started working with IE this was the first exception, which I used to get, and I was sure that this related to some browser setting.) We can solve this issue using do some setting in internet explorer. To enabling one by one all security zones in internet options of IE.
ü Unexpected error launching Internet Explorer.Browser zoom level was set to 0%. (By the name itself, you can see that we have to set the zoom level to 100 % to make it work.)
ü Handle Untrusted SSL certificate error in IE browser in different ways Solution: IE is the product of Microsoft and IE is much worried about security so when you start working with some https application you will get a untrusted certificate. Selenium has so many ways to handle this, but we will see 2 ways which work all the time for me. 1. Open the application for which SSL certificate is coming so use below code after passing the URL. driver.get(“ur app URL”); driver.navigate().to(“javascript:document.getElementById(‘overridelink’).click()”); // you can use your code now. 2. You can handle this certificate using Desired Capabilities as well. To accepting untrusted ssl certificates.
************************------------------******************
35- Have you ever faced any proxy issue if yes then how you handled?
Ans:
Handle proxy in Selenium Webdriver
When you try to access some secure applications you will get proxy issues so many times. Until we
do not set proxy, we cannot access the application itself.
Handle Proxy in Selenium Webdriver
1- Change the proxy setting manually and open default browser.
2- Change the proxy setting using Webdriver code.
In this post, we will see second approach
To handle proxy setting in Selenium we have separate class called Proxy that is available inside org.openqa.selenium package
Sample Demo Code:
import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities;
public class ProxyDemo {
public static void main(String[] args) {
// Create proxy class object
Proxy p=new Proxy();
// Set HTTP Port to 7777
p.setHttpProxy("localhost:7777");
// Create desired Capability object
DesiredCapabilities cap=new DesiredCapabilities();
// Pass proxy object p
cap.setCapability(CapabilityType.PROXY, p);
// Open firefox browser
WebDriver driver=new FirefoxDriver(cap);
// from here onwards code will be same as normal script
}
}
************************------------------******************
36- What is Actions class in Selenium (How to perform Mouse Hover, Keyboard events, DragAndDrop etc?)
Ans-In Webdriver, handling keyboard events and mouse events (including actions such as Drag and Drop or clicking multiple elements With Control key) are done using the advanced user interactions API . It contains Actions and Action classes which are needed when performing these events. For all advance activity in Selenium Webdriver we can perform easily using Actions class like Drag and Drop, mouse hover, right click, clickandhold, releasemouse many more. We have predefined method called dragAndDrop(source, destination) which is method of Actions class.
To use mouse actions, we need to use current location of the element and then perform the action.The following are the regularly used mouse and keyboard events:
Method :clickAndHold() Purpose: Clicks without releasing the current mouse location
Method: doubleClick() Purpose: Performs a double click at the current mouse location
Method: dragAndDrop(source,target) Parameters: Source and Target Purpose: Performs click and hold at the location of the source element and moves to the location of the target element then releases the mouse.
Method : dragAndDropBy(source,x-offset,y-offset) Parameters: Source, xOffset - horizontal move, y-Offset - vertical move Offset Purpose: Performs click and hold at the location of the source element moves by a given off set, then releases the mouse.
Method: keyDown(modifier_key) Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL) Purpose: Performs a modifier key press, doesn't release the modifier key. Subsequent interactions may assume it's kept pressed
Method: keyUp(modifier_key) Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONROL) Purpose: Performs a key release.
Mouse Hover:
public class mouseHover{
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.onlinestore.toolsqa.com");
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("iPads")).click();
}
}
Drag and Drop Example
public class DemoDragDrop {
public static void main(String[] args) throws Exception {
// Initiate browser
WebDriver driver=new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Open webpage
driver.get("http://jqueryui.com/resources/demos/droppable/default.html");
// Add 5 seconds wait
Thread.sleep(5000);
// Create object of actions class
Actions act=new Actions(driver);
// find element which we need to drag
WebElement drag=driver.findElement(By.xpath(".//*[@id='draggable']"));
// find element which we need to drop
WebElement drop=driver.findElement(By.xpath(".//*[@id='droppable']"));
// this will drag element to destination
act.dragAndDrop(drag, drop).build().perform();
}
}
************************------------------******************
37- Do we have object repository concept in Selenium if yes then please explain how we can achieve it?
Ans-Yes We have object Repository concept in selenium. Whenever you talk about repository by the name itself you can think that it is kind of storage. Object repository is the collection of object and object here is locator. Here locator means web element id, name, CSS, XPath, class name etc. Basically we can use object repository in automation framework because we need to handle huge amount of element locator separate so that it easy to handle and maintain.
************************------------------******************
38- What is Headless testing? Can we capture Screenshot in Headless mode?
Ans-If you have ever worked on Firefox, Chrome, IE browser in Selenium you might have faced so many issues like xpath is changing every time when new feature is getting added. Using these browser, some common issue which I faced during my daily automation like Sync issues and speed as well. Some browser takes time to load in my experience I faced performance issues with IE browser. To increase speed of your test script i.e. performance of your script we can try some testcases using Headless Browser Testing using Selenium.
Headless Testing / Headless Browser:
A browser, which does not have any GUI it means which runs in background. If you run your programs in Firefox, Chrome, IE and different browser then you can see how the browser is behaving but in headless browsers, you cannot.
Advantage and Disadvantage of headless browsers
One of the most Important advantage is Performance.
1-When we run your test case using headless browsers then you will get result just in seconds, you will see the result in below program. 2-When we have to run test case to create some sample test data or just you have to verify some messages and functionality then you can should try headless browsers. 3- When we have to run test case in remote machine or server, which does not have any browser, but still you have to execute test case then you can try with headless browsers again. I hope you get the clear picture of this so let us start with some program and output as well. There are so many headless browser available in market, which do the same like Nodejs etc. When you build your test case using Jenkins then also it run in Headless mode
Program for headless Testing:
public class HtmlDemoProgram1 {
public static void main(String[] args) throws InterruptedException {
// Declaring and initialize HtmlUnitWebDriver
WebDriver driver = new HtmlUnitDriver();
// open facebook webpage
driver.get("http://www.facebook.com");
// Print the title
System.out.println("Title of the page "+ driver.getTitle());
// find the username field
WebElement username = driver.findElement(By.id("email"));
// enter username
username.sendKeys("mukeshotwani.50@gmail.com");
// find the password field
WebElement password = driver.findElement(By.id("pass"));
// Click the loginbutton
password.sendKeys("pjs@903998");
// find the Sign up button
WebElement Signup_button = driver.findElement(By.id("loginbutton"));
// Click the loginbutton
Signup_button.click();
// wait for 5 second to login
Thread.sleep(5000);
// You will get new title after login
System.out.println("After login title is = " + driver.getTitle());
}}
************************------------------******************
39-Diffrence between findElement and FindElements?
Ans-findElement () will return only single WebElement and if that element is not located or we use some wrong selector then it will throw NoSuchElement exception.findElements() will return List of WebElements – for this we need to give locator in such a way that it can find multiple elements and will return you list of webelements then using List we can iterate and perform our operation.
************************------------------******************
40- Can we highlight Element in Selenium?
Ans-Yes. In Selenium, we can use JavascriptExecutor (interface) to execute Javascript code into webdriver. In this post we, will execute Javascript which will highlight the element.
Code:
public class Highlight {
public static void main(String []args){
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
// Create the JavascriptExecutor object
JavascriptExecutor js=(JavascriptExecutor)driver;
// find element using id attribute
WebElement username= driver.findElement(By.id("email"));
// call the executeScript method
js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'')", username);
}
}
************************------------------******************
41- What is log4j and How to generate log files in Selenium?
Ans- Log4j:Log4j is free open source tool given by Apache foundation for creating log files It help us to generate log file in various output target.
Generate Log Files: In my automation framework I use these following steps.
Step1: Download log4j.jar and add into your project.
Step2. Then create log4j.xml. That are some available log4j files on internet.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"><appender name="fileAppender" class="org.apache.log4j.FileAppender"><param name="Threshold" value="INFO" /><param name="File" value="src/config/Application.log"/><layout class="org.apache.log4j.PatternLayout"><param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" /></layout></appender><root><level value="INFO"/><appender-ref ref="fileAppender"/></root></log4j:configuration>
Step3: We need to add Log.Java and then we can used logs in our automation framework that can we see while running script in console and the above log4j.xml files create application.log file.
public class Log { // Initialize Log4j logs private static Logger Log = Logger.getLogger(Log.class.getName());
public static void info(String message) { Log.info(message); }} //We can create a lots of method like warn, error, fatal, etc as per our need. ************************------------------******************
42-How to capture Page title, tooltip and error message and how to verify them?
Ans-Verify Page title:
public class verifyTitle {
WebDriver driver = new FirefoxDriver();
String title;
@Test
public void getTitlePage()
{
driver.get("https://www.salesforce.com/login");
driver.manage().window().maximize();
title = driver.getTitle();
System.out.println("Page title is: "+title);
Assert.assertTrue(title.contains("salesforce.com"));
driver.close();
}
}
Verify Tooltip:
public class Tooltip {
public static void main(String[] args) {
// This will open browser
WebDriver driver=new FirefoxDriver();
// This will maximize your browser
driver.manage().window().maximize();
// Open Gmail account creation page
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
// Click on username textbox
driver.findElement(By.xpath(".//*[@id='GmailAddress']")).click();
// Create action class object
Actions builder=new Actions(driver);
// find the tooltip/helptext message xpath
WebElement username_tooltip=driver.findElement(By.xpath("html/body/div[2]/div[1]"));
// Mouse hover to that text
builder.moveToElement(username_tooltip).perform();
// Extract the text from tooltip using getText
String tooltip_msg=username_tooltip.getText();
// Print the tooltip message
System.out.println("Tooltip message is "+tooltip_msg);
// This is expected message should come and store in variable
String expected_tooltip="You can use letters, numbers, and periods.";
// It will compare if actual matches with expected then TC will fall else it will fail
Assert.assertEquals(tooltip_msg, expected_tooltip);
System.out.println("Message verifed");
}
}
Verify Error Message:
public class TestNaukri {
@Test
public void TestError()
{
// Open browser
FirefoxDriver driver=new FirefoxDriver();
// maximize browser
driver.manage().window().maximize();
// Open URL
driver.get("http://www.naukri.com/");
// Click on login button
driver.findElement(By.id("p0submit")).click();
// This will capture error message
String actual_msg=driver.findElement(By.id("emailId_err")).getText();
// Store message in variable
String expect="plz enter valid email";
// Here Assert is a class and assertEquals is a method which will compare two values if// both matches it will run fine but in case if does
not match then if will throw an
//exception and fail testcases
// Verify error message
Assert.assertEquals(actual_msg, expect);
}
}
************************------------------******************
43-How to download files in Selenium?
Ans-publicclassFileDownloadExample
{
publicstatic String downloadPath = "D:\\seleniumdownloads";
@Test
publicvoidtestDownload() throws Exception
{
WebDriver driver = newFirefoxDriver(FirefoxDriverProfile()); driver.manage().window().maximize();
driver.findElement(By.linkText("smilechart.xls")).click();
}
publicstatic FirefoxProfile FirefoxDriverProfile() throws Exception
{
FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.manager.showWhenStarting", false); profile.setPreference("browser.download.dir", downloadPath); profile.setPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.msexcel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.alwaysAsk.force", false); profile.setPreference("browser.download.manager.alertOnEXEOpen", false); profile.setPreference("browser.download.manager.focusWhenStarting", false); profile.setPreference("browser.download.manager.useWindow", false); profile.setPreference("browser.download.manager.showAlertOnComplete", false); profile.setPreference("browser.download.manager.closeWhenDone", false);
return profile;
} }
We will explain you the preferences that we have set to Firefox browser.
setPreference("browser.download.folderList", 2); Default Value: 1 The value of browser.download.folderList can be set to either 0, 1, or 2. When set to 0, Firefox will save all files downloaded via the browser on the user's desktop. When set to 1, these downloads are stored in the Downloads folder. When set to 2, the location specified for the most recent download is utilized again.
setPreference("browser.download.manager.showWhenStarting", false); Default Value: true The browser.download.manager.showWhenStarting Preference in Firefox's about:config interface allows the user to specify whether or not the Download Manager window is displayed when a file download is initiated.
browser. helperApps. alwaysAsk. force True: Always ask what to do with an unknown MIME type, and disable option to remember what to open it with False (default): Opposite of above
browser. helperApps. neverAsk. saveToDisk A comma-separated list of MIME types to save to disk without asking what to use to open the file. Default value is an empty string.
browser. helperApps. neverAsk. openFile A comma-separated list of MIME types to open directly without asking for confirmation. Default value is an empty string.
browser. download. dir The last directory used for saving a file from the "What should (browser) do with this file?" dialog.
browser.download.manager.alertOnEXEOpen True (default): warn the user attempting to open an executable from the Download Manager False: display no warning and allow executable to be run Note: In Firefox, this can be changed by checking the "Don't ask me this again" box when you encounter the alert.browser. download. manager. closeWhenDone True: Close the Download Manager when all downloads are complete False (default): Opposite of the above
browser. download. manager. focusWhenStarting True: Set the Download Manager window as active when starting a download False (default): Leave the window in the background when starting a download
************************------------------******************
44- Have you ever performed Database testing in Selenium?
No.
************************------------------******************
45- Have you integrated Selenium with other tools like Sikuli, Ant, Maven, and Jenkins? If yes, then how you have used them?
Ans- Yes I am very much interested. Currently I am using Ant in my automation framework. And I am planning to use maven in next project. But individually I have performed some demo on Sikuli, maven, Jenkins as well.
************************------------------******************
46- Does Selenium support Mobile Automation if yes then How?
Ans-Yes. But it needs some external tools to communicate with mobile app and perform automation. There is various tool available for mobile automation. Robotium, Monkey-runner, Ranorex, Appium and UI Automator.
************************------------------******************
47- What is Limitation of Selenium?
Ans-Some limitations of Selenium Automation tool are as follows:
1. It does not support and non-web-based applications, it only supports web based applications. 2. You need to know at least one of the supported language very well in order to automate your application successfully.
3. No inbuilt reporting capability so you need plugins like JUnit and TestNG for test reports. 4. Lot of challenges with IE browser.
************************------------------******************
48- Have you ever heard of POC? What is POC?
Ans-Proof of Concept in Automation Testing
How we create POC for current project/ application?Why POC is important for Automation testing?What is POC in Automation? A POC stands for Proof of Concept. It is just a document or some time a demo piece of code, which describe points, and some questions/answer. In Other words- It simply words that we have to proof that what are doing and what will be outcome of the same. Example- When we are running automation script for some testcase what will be total saving or effort you have saved via automation and so on. How we create POC for current project/ application? While creating POC documents/dem you should be ready with some Points.
1. What type of your application/project we are Automating? Answer can be a web-based application or a desktop application or mobile application or some other type of application?
2. In your project, what type of testing tasks will be performed? Answer can be smoke testing, regression testing and sometime E2E (End to End)test cases also etc.
3. Does your company have budget for same? Does it be willing to go in for high-end commercial tools like QTP or would it only free tools (Selenium)?
4. Identify the task which has to be done before automation? It can be setting up the setting up your application, test data, setting the project / setup of tools etc. After discussion of all above question, let us conclude below points
1. Select one or two suitable tool. Important point-If it is a commercial tool then you could probably get a trial version of the same or ask demo for paid product and if it matches with your requirement then go for it.If it is free-ware then check the limitation of the tool and compare both tools.
2. For each tool, create a simple automation script for desired testing tasks and compare the result, pros and cons.
3. When you have the automation-working fine then you can present it to your manager, lead, or client for next action. If they agree then you can adapt the same
Proof of Concept in Automation Testing
POC document is very important for companies before moving to automation like why they should move to manual to automation. What will be saving- Effort saving/ Time saving/Money saving etc. Because automation tools require kind of programming knowledge. POC document will give result that whether we should move from Manual to Automation for the fowling project or not.
************************------------------******************
49- What is ATLC (Automation Test life Cycle)?
Ans-
Let’s start each of the phase of Automation test life cycle.
1- Automation feasibility analysis
In this section you have to think from different perspective. The main objective of this phase will be to check feasibility of automation.
1- Which test case can be automated and how we can automate them. 2- Which module of your application can be tested and which cannot be automated. 3- Which tools we can use for our application (like Selenium,QTP,Sahi,OATS, Telrik etc) and which tools will be best of our application. 4- Take following factors into consideration like Team size,Effort and cost involved for tools which we will use.
2- Test Plan/Test Design
This phase plays very important role in Automation test life cycle. In this phase you have to create a Test plan by considering below point into considerations.
1- Fetch all the manual test case from test management tool that which TC has to automate. 2- Which framework to use and what will be advantage and disadvantage of the framework which we will use.
3- Create a test suite for Automation test case in Test Management tool.
4- In test plan you can mention background, limitation, risk and dependency between application and tools.
1- Approval from client/ Stack holders.
3- Environment Setup/Test lab setup
By name itself you can understand that we need to setup machine or remote machine where our test case will execute.
1- In this section you can mention how many machine you want.
2- What should be the configuration in terms of hardware and software.
4-Test Script development/ Automation test case development
In this phase you have to start develop automation script and make sure all test script is running fine and should be stable enough.
1- Start creating test script based on your requirement
2- Create some common method or function that you can reuse throughout your script.
3- Make your script easy, reusable, well-structured and well documented so if third person check your script then he/she can understand your scripts easily.
4- Use better reporting so in case of failing you can trace your code
5- Finally review your script and your script should be ready before consumption.
5-Test script execution
Now its time for execution of test scripts, in this phas you have to execute all your test script.
Some points to remember while execution.
1- Your script should cover all the functional requirement as per testcase.
2- Your script should be stable so it should run in multiple environment and multiple browsers (depends on your requirement)
3- You can do batch execution also if possible so it will save time and effort.
4- In case of failure your script should take screen shots.
5- If test case is failing due to functionality, you have to raise a bug/defect.
6- Generate test result / Analyses of result
This is the last phase of Automation test life cycle in which we will gather test result and will share with team/client/stack holders.
1- Analyze the output and calculate how much time it takes to complete the testcase.
2- You should have good report generation like XSLT report, TestNG report, ReporterNG etc.
************************------------------******************
50- What is Automation Test Plan? Ans-
Section #1: Scope
- Choose the test cases/scenarios that are to be regressed over and over across multiple cycles.
- Sometimes the simplest of test cases need lots of complicated solutions to be automated. If these are just for a one time use, it obviously does not make sense. Reusability should be your focus.
- Automation Testing does not/cannot perform exploratory testing.
- This section is referred to as Framework in the automation world. Some frameworks are extremely challenging to create and also are effective – but time, effort and competency wise they are demanding. Always look for a middle ground and do the best you can without jeopardizing over utilization of resources.
- Decide on coding best practices to be used, naming conventions, locations for test assets to be stored, format of test results, etc. to maintain uniformity and increase productivity.
Section #3: Resources/roles and responsibilities
- The first step in this direction is to understand the team’s capabilities and anticipate ahead the scope of automation coming into picture. This will help choose a team that suits both the automation and manual testing needs. Also, pick people who have the right attitude – those do not think that manual testing is beneath their stature.
- Choose a team well versed with AUT, test management, defect management and other SDLC activities
- Section #1: Scope
Section #4: Tools
Pick automation tools based on the following rules:
- Does the company already have licenses for a certain tool, try and see if you can use it?
- Look for open source (but reliable) tools
- Do the team members know the tool already or do we need to bring in someone new? Or train the existing ones?
Section #5: Schedules
- Include time for code-walkthroughs and inspection of the automation scripts
- Maintain the scripts on a timely basis. If you create a piece of code that you are not going to use for the next 6 months or so, make sure to periodically maintain it to lessen its chances of failure.
Section #6: Environment
- The target environment that your AUT is going to run and the automation tool that you want to use should be compatible. This is one of the factors to be considered pre-licensing for the tool.
- Also, analyze if the rest of the management tools in place and the automation tool you are trying to bring in are inter-connectible for additional benefit.
Section #7: Deliverables
- Your test scripts are your deliverables. However, not everyone is automation/programming language savvy. So, plan on creating a “How-to” document that will help the current users and future team members to be able to understand this script even when you are not around.
- Include comments in your script too.
If you are going to propose an automation solution, be sure to choose cost effective tools and solutions to make sure that the automation endeavor does not burden the project. It is important to set the expectation that ROI for an automation project cannot be positive immediately but can be clearly seen over long periods of time.
Therefore, if you propose automating a system, pick the one that is
- Stable and not too much maintenance
- Has a scope for huge regression suites
- Does not have too much of manual intervention or does not depend of a human’s intuition
Section #9: Test data
- Take into consideration the security aspects of the data
- Do not hard code any test data into the scripts. This just leads to too much script maintenance and might induce errors during modification.
- Be very specific. For a manual test step – ‘enter first name’, you can say enter any 5 character name. While testing, a tester can type “Swati” or “seela” or anything else. But for a tool it can’t make such suppositions. Therefore, provide exact values.
Section #10: Reports/results
- Script execution results are also technical and might not be easily understood by the rest of the teams. Plan on writing detailed results to notepad or excel sheets as an additional measure.
- Detailed framework documents, review results, defect reports, execution status reports are also expected.
************************------------------******************
Selenium Webdriver/RC/IDE Interview questions and Answers
All these question that we discussed now that is the combination of all level (Beginner, Advance).
They will definitely ask so many questions from Framework itself and they will try to drag you in this topics because most of the people will stuck and interviewer will get to know that person has actually worked on Selenium or not.
Please make sure you are giving proper answer
52- Have you designed framework in your team or you are using existing framework, which already implemented by other members?
Ans-Yes. I have implemented and created framework in my team.
************************------------------******************
53- Can you create design of your framework?
Ans- Yes.
************************------------------******************
54- Which framework you have used and why?
Ans- I have created Data-Driven Framework with some capabilities of Page object model framework. After analyzing condition of project I recommend myself to make data driven framework. And after sometime added some functionalities. As per what I need. And the most important thing is that it easier maintain and create.
************************------------------******************
55- Can you create one sample script using your framework?
Ans- No. Because it needs to take time to make framework. And at same time I did not know all the things but I can.
************************------------------******************
There is again no limitation or specific question so be ready with any type of question but make sure whenever you are giving answer it should have valid point or you can directly say that I am not sure about it.
If you answer 6-7 out of 10 then it is enough.
We have more question for you, which you must know because we all have worked on TestNG with Selenium and it is one of my favorite Tool, which I have used it with Selenium and I really enjoyed a lot.
Since TestNG is not a very big tool so do not worry about it and it has very good documentation on their official site so if you want to check then check out below link –
Here is a list of questions for TestNG
56- What is TestNG?Ans: TestNG is a testing framework inspired from JUnit and NUnit, but introducing some new functionalities that make it more powerful and easier to use.
TestNG is an open source automated testing framework; where NG means Next Generation. TestNG is similar to JUnit (especially JUnit 4),
but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes.
TestNG Features Supports annotations.
1. TestNG uses more Java and OO features.
2. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every test method).
3. Separates compile-time test code from run-time configuration/data info.
4. Flexible runtime configuration.
5. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the "front-end" tests, or "fast", "slow", "database" tests, etc.
6. Supports Dependent test methods, parallel testing, load testing, and partial failure.
7. Flexible plug-in API.
8. Support for multi threaded testing.
************************------------------******************
57- Why you have used TestNG in your framework? Can you compare JUNIT with TestNG framework?
Ans: Difference between testng and junit.
1. WebDriver has no native mechanism for generating reports.
2. TestNG can generate the report in a readable format
3. TestNG simplifies the way the tests are coded
4. There is no more need for a static main method in our tests.
The sequence of actions is regulated by easy-to-understand annotations that do not require methods to be static.
5. Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely. These exceptions are reported as failed steps in the report.TestNG fares better than JUnit on following parameters.
1) Support for Annotations
Both the frameworks have support for annotations. In JUnit 4, the @BeforeClass and @AfterClass
methods have to be declared as static.
TestNG does not have this constraint. TestNG has provided three additional setup/teardown pairs
for the suite, test and groups, i.e. @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest,
@BeforeGroup and @AfterGroup.
2) Dependent Tests
We cannot create dependent tests in JUnit. It’s possible only in TestNG.
TestNG uses “dependOnMethods” to implement the dependency testing as following.
@Test
public void test1()
{
System.out.println(“This is test 1”);
}
@Test(dependsOnMethods={“test1”})
public void test2()
{
System.out.println(“This is test2”);
}
The “test2()” will execute only if “test1()” is run successfully, else “test2()” will skip the test.
3) Parallel Execution of the tests
JUnit does not have inherent support for parallel execution. However, we can use maven-
surefire-plugin and Gradle test task attribute maxParallelForks to execute the tests in
parallel. TestNG has inherent support for parallelization by means of “parallel” and “thread-count” attributes in . @Test annotation has threadPoolSize attribute.JUnit is often shipped with mainstream IDEs by default, which contributes to its wider
popularity. However, TestNG’s goal is much wider, which includes not only unit testing, but also support of integration and acceptance testing, etc. Which one is better or more suitable depends on use contexts and requirements.
4) In TestNG, Parameterized test configuration is very easy while It is very hard to configure
Parameterized test in JUnit.
5) TestNG support group test but it is not supported in JUnit.
6) TestNG support @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite, @BeforeGroups,
@AfterGroups which are not supported in JUnit.
7) Test prioritization, Parallel testing is possible in TestNG. It is not supported by JUnit.
************************------------------******************
58- What are different annotation present in TestNG?
Here is the list of annotations that TestNG supports:
Annotation
|
Description
|
@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 <test> tag is run.
|
@AfterTest
|
The annotated method will be run after all the test methods belonging to the classes inside the <test> 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.
|
|