[go: up one dir, main page]

0% found this document useful (0 votes)
47 views13 pages

Selenium Interview Questons

Uploaded by

hiten patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views13 pages

Selenium Interview Questons

Uploaded by

hiten patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

** Hello guys, this file contents FAQ’s with answers for selenium.

I tried to add questions


which are asked at interviews and tried to cover most of topics. Im giving u all privileges so
can make changes in this file. But please guys keep in mind don't delete any
content from the file. If you will find anything wrong or you have a better answer than
current, then comment it with giving your name as tag. You can share this file with anybody
but give all privileges to only who have good experience into selenium.***Thanks

1. POM-Page Factory
@FindBy(name="txtUserID")
WebElement txtUserID
PageFactory.initElements(driver, this)

Dynamic @FindBy annotation


@FindBy(how = How.ID, using = "somelocator_with_a dynamic_${id}")

@FindAll({@FindBy(how=How.ID, using=”username”),
@FindBy(className=”username-field”)})
private WebElement user_name;

difference between @FindAll and @FindBys annotations in webdriver page factory-


@FindBys : When required web-element(s) need to match all of the given criteria use
@FindBys annotation
@FindAll : When required web-element(s) need to match at least one of the given criteria
use @FindAll annotation
* FindBy annotation to replace driver.findelement(By x) statements in our POM
code
*for driver.findelements(By x)-
@FindAll({@FindBy(xpath = “yourxpath”)})
public List<WebElement> resultElements;

*You can also use this to group different FindBy into a WebElement list
@FindAll({@FindBy(xpath = “yourfirstxpath”),@FindBy(xpath =
“yoursecondxpath”),@FindBy(xpath = “yourThirddxpath”)})
public List<WebElement> resultElements;

2. Handle dropdown- Done with creating object of Select class


WebElement element=driver.findElement(By.name("Mobiles"));
Select se=new Select(element);
se.selectByVisibleText("HTC");
3. ArrayList, hashmap, hashtable, Vector, HashSet
ArrayList- Dynamic Array- Array lists are created with an initial size. When this size is
exceeded, the collection is automatically enlarged. When objects are removed, the array
may be shrunk. Methods Add and Remove.
Vector- Same as ArrayList but the difference is Vector is synchronized and Vector
contains many legacy methods that are not part of the collections framework.Methods
AddElement and RemoveElement

HashMap-
A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
it is not synchronized
Iterator we use for iteration
Methods- put- with key and value
remove- by passing key

HashTable- Same as HashMap but this is Synchronized. So hashtable is better for NON
thread Applications and HashTable does NOT allow null kays values. Enumerator we use
for iteration

4. JavaScript- why Javascriptexecutor?


Verifying images
Checking scrollbars
Manipulating (or clearing) HTML5 local & session storage
Drag & Drop
Mouse over
Mouse click
Highlighting elements
((JavascriptExecutor)driver).executeScript("arguments[0].style.border='3px solid red'",
elem);

Why should NOT use JavascriptExecutor


If we used javascript we didn't have to wait for the button to be visible.

eg1. JavascriptExecutor js = (JavascriptExecutor)driver;


js.executeScript("arguments[0].click();", element);
eg2.
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
5. ALert handle
Web Alerts-
driver.switchTo().alert().dismiss()/Accept/getText/sendKeys;
Window Based Alerts-Upload/Download File
Using Robot class
Using AutoIT
6. Run tests on chrome
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
7. Run tests on IE
System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe");
driver = new InternetExplorerDriver();
8. XPath-
-Absolate XPath-
--Starts with SIngle forward slash('/') OR Root Node
--This is Fast
--This xpath contains long path ie. whole path
-Relative XPath
--Starts with double forward slash('//')
--Do not need to have whole path from root node
--Its slow comparatively Absolute XPath
--If multiple elements found, then first element will get identified

-Below are the ways we can use Relative path


-- Starts-With method
eg. //id[starts-with(@id,’’)],//a[starts-with(@href=’’)], //img[starts-with(@src=’’)],
//div[starts-with(@id=’’)],
//input[starts-with(@id=’’)], //button[starts-with(@id,’’)]
-- Contains Method
eg. //tagname[contains(@attribute,’value1’)]
-- Text Keyword
eg.
-- Using SIngle attribute
eg. //s[@id='ID10000']
-- Using Mutiple Attributes
eg. //s[@id='ID10000'][@name='ObjectName']
-- Using Following Node- It searches in the siblings in the same parent
eg. //input[@id=’’]/following::input[1]
[AKSHAY] - Checked for Chrome browser and from blogs came to know that for many
case the above instruction does not work hence there is a modified version that can be
used for all the cases,
//input[@id=’’]/../following-sibling::input[1]
-- Using Preceeding Node
eg. //input[@id=’’]/ preceding::input[1]
-- Using ANS or OR
//*[contains('abc') or contains('def') or text()='abcdef']

9. Synch ways
1. Unconditional
2. Conditional Synchronization
3. PageLoadTimeout
4. Thread.Sleep
[AKSHAY] - As per my understanding Synchronization is of 2 types, Implicit (Conditional)
and Explicit (Unconditional),
Implicit type -- Wait the application unless and until certain period of time in order to see a
condition set’s True.
E.g. driver.manage().timeouts().implicitlyWait(2, TimeUnit.Minutes)
So the above instruction will wait for 2 Min, or less unless a particular element is
visible/available.
The 3rd point mentioned above Page Load Timeout is also a part of Implicit wait that wait’s
for the webpage to be loaded completely. Majorly used where the connectivity with the
application is slow or if there is any performance issue with the application.

Explicit type - Wait for a desired set of period/time before doing any other action/operation.
E.g. Thread.sleep(5000);
So above instruction will wait for 5 sec irrespective of whether the element is
visible/available or not.

10. Count No of objects on webpage.


List<WebElement> items = driver.findElements(By.cssSelector("*"));
System.out.println(items.size());

11. Frames handling- driver.switchto.frame(frame ID/Index/name);


Handle Child Frames-
driver.switchTo().frame(ParentFrame).switchTo().frame(ChildFrame);
Count No of frames on webpage-
//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer numberOfFrames = Integer.parseInt(exe.executeScript("return
window.length").toString());
System.out.println("Number of iframes on the page are " + numberOfFrames);
//By finding all the web elements using iframe tag
List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
System.out.println("The total number of iframes are " + iframeElements.size());
Switching back to Main page from Frame
driver.switchTo().frame(0);
//Do all the required tasks in the frame 0
//Switch back to the main window
driver.switchTo().defaultContent();
12. Desired Capabilities- DesiredCapabilities help to set properties for the WebDriver.
It gives facility to set the properties of browser. Such as to set BrowserName, Platform,
Version of Browser.
Mostly DesiredCapabilities class used when do we used Selenium Grid.

13. TestNG Reports- ReportNG and adding listeners to textng.xml

14. Press keyboard keys- Using Actions


Using Sendkeys-
driver.findElement(By.xpath(id("anything")).sendKeys(Keys.CONTROL + "a");
Using Actions
Actions action = new Actions(driver);
// Hold Control
action.keyDown(Keys.CONTROL);
action.perform();

Using JavaScriptExecutor
Using Robot Class

15. Screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

16. How to verify image?


OCR
Sikuli
im4java n imagemagick

17. Ways to check object exist or not on webpage


Size method
Exist property
Using Try Catch block
isEmpty
assertElementFound
isDisplayed()
By using Page Factory- @FindBy annotation

18. Selenium webdrivers exceptions


ElementNotSelectableException
ElementNotVisibleException
InvalidSwitchToTargetException
NoAlertPresentException
NoSuchElementException

19. Database Connection


1. DB URL- String dbUrl = "jdbc:mysql://localhost:3036/emp";
2. Class.forName("com.mysql.jdbc.Driver");
3. Connection con = DriverManager.getConnection(dbUrl,username,password);
4. Statement stmt = con.createStatement();
5. ResultSet rs= stmt.executeQuery(query);
20. Table values- size method to get no rows and columns
tbody as container
tr is Row
td is column
th is Column Title

colElement = row.findElement(By.xpath(".//td[" + colIndex + "]"));


System.out.println(colElement.getText().trim());

21. Date difference-


format both dates by using format.parse
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
long diff= d1-d2;
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

22. Get no of rows and columns in xls file


int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells(); OR
int noOfColumns = sh.getRow(0).getLastCellNum(); OR
by using rowitarator we can cont no of rows

23. HTMLUnitDriver- HTML unit driver is the most light weight and fastest implementation
headless browser for of WebDriver.It is known as Headless Browser Driver.It is same as
Chrome, IE, or FireFox driver, but it does not have GUI so one cannot see the test
execution on screen.
[AKSHAY] - Use of Headless browser is mostly used to do Performance Testing, Running
automated tests for JavaScript libraries, where we don’t need to see or view any
screenshots for any pass or fail criteria.
Another example of Headless Browser is PhantomJS, [RAM]TrifleJS, Splash which are also
used in Selenium.

24. Firefox Preference- We can take help from about:config by entering FF browser
Set yahoo.com as startup page in FF
FirefoxProfile ffprofile= new FirefoxProfile();
profile.setPreference("browser.startup.homepage","http://www.yahoo.com");
driver = new FirefoxDriver(ffprofile);// We can use above profile by passing as a
parameter

25. xls Filter- By using XSSFAutoFilter setAutoFilter(CellRangeAddress range)

26. garbage collection forcefully.--- System.gc();

27. In which scenario we use interface and abstract class?


If we don't know complete implementation about set of services then we should go for
interface only.
if you know partial implementation about set of services then we should go for abstract
class.
If we want to stop instantiation(creation of object) of a class then we should go for
abstract class.

28. Asserts
Assert.assertTrue() & Assert.assertFalse()
Assert.assertEquals()
assertEqualsNoOrder
assertNotNull
assertNotSame
29. Passing xls data to DataProvider- By using FileInputSTream and iterating through
every cell.

30. How to find element which is NOt visible in DOM but its visible in browser?
isDisplayed can be used to test if an element is visible right now, not if it exists in the dom

31. Explicitwait-
Explicit waits are done using the WebDriverWait and ExpectedCondition classes.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
ExpectedConditions- isEnabled, isDisplayed,isSelected

32. Checked/UnChecked Exception-


Checked exceptions are the exceptions that are checked at compile time. If some code
within a method throws a checked exception, then the method must either handle the
exception or it must specify the exception using throws keyword.
UnChecked Exceptions- are the exceptions that are not checked at compiled time. In C+
+, all exceptions are unchecked, so it is not forced by the compiler to either handle or
specify the exception. It is up to the programmers to be civilized, and specify or catch the
exceptions.

33. Custom Exception in Java


class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}

34. Properties file


FileInputStream
Properties prop = new Properties()
prop.load(fileInput);
System.out.println(prop.getProperty("Key"));

35. RemoteDriver
String hubURL = "http://myip:4444/wd/hub";
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
WebDriver driver = new RemoteWebDriver(new URL(hubURL), capability);
driver.get("http://www.google.com");

36. Static Block


Called when class is loaded to JVM

Disadvantages
You cannot throw Checked Exceptions.
You cannot use this keyword since there is no instance.
You shouldn’t try to access super since there is no such a thing for static blocks.
You should not return anything from this block.

37. Static Variables


It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution . These variables
will be initialized first, before the initialization of any instance variables

38. Static Methods


It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data (instance
variables)
A static method can call only other static methods and can not call a non-static method
from it.
A static method can be accessed directly by the class name and doesn’t need any object
A static method cannot refer to “this” or “super” keywords in anyway

39. Download file- WGet


Wget is a small and easy-to-use command-line program used to automate downloads.

40. Challenges faced in Selenium with solution-


- Selenium does not support window based application- Used AutoIT
- There is no object repository concept in Selenium, so maintainability of the objects is
very high- Used POM and Page Factory
- To generate report we need to take help from other tools
- Testing dynamic text or content
Problems with IE browser-
- The path to the driver executable must be set by the webdriver.ie.driver-
Sysyem.setProperty
- Unexpected error Browser zoom level- Need to zoom level 100%
- Sendkeys method works slowly

41. Log4J if files size exceeds what happens?


"maxFileSize" is used to configure the maximum size of the log file. When file reaches
this size, a new file will be created with the same name and the old file name will be
add as an Index to it.
42. How log4j is used within script?
Logger log = Logger.getLogger("devpinoyLogger");
log.debug("--information--");
43. what are the files we need to do setup for Log4j?
First file will include all the log4j configuration
for eg. log4j.properties file
Second file as Manual.log which includes manually logged statements

44. What are the Benefits of Robot API?


Robot API can simulate Keyboard and Mouse Event
Robot API can help in upload/download of files when using selenium web driver
Robot API can easily be integrated with current automation framework (keyword, data-
driven or hybrid)
45. Handle ajax calls
waitForCondition
waitForNotVisible
waitForSelectOptions

46. Window handler


Set handles = driver.getWindowHandles();
firstWinHandle = driver.getWindowHandle();
handles.remove(firstWinHandle);
String winHandle=handles.iterator().next();

47. getLocation Command- This method locate the location of the element on the page.
This accepts nothing as a parameter but returns the Point object.

48. WebElement element = driver.findElement(By.id("SubmitButton"));


Point point = element.getLocation();
System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);

49. Find broken links


List elementList = new ArrayList();
elementList = driver.findElements(By.tagName("a"));
List finalList = new ArrayList();
for (WebElement element : elementList)
{
if(element.getAttribute("href") != null)
{
finalList.add(element);
}
}

50. private access modifier- The private access modifier is accessible only within class.
default access modifier - If you don't use any modifier, it is treated as default bydefault.
The default modifier is accessible only within package.
protected access modifier - The protected access modifier is accessible within package
and outside the package but through inheritance only.The protected access modifier
can be applied on the data member, method and constructor. It can't be applied on the
class.
public access modifier - The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.

51. How to getTag name of an element?


String tagName;
tagName = driver.findElement(By.id("email")).getTagName();

52. Refresh Browser by 5 ways


driver.navigate().refresh();
driver.findElement(By.name("s")).sendKeys(Keys.F5);
driver.navigate().to(driver.getCurrentUrl());
driver.findElement(By.name("s")).sendKeys("\uE035");

53. ******By.cssSelector() does not support the "contains" feature*****


******Parameter value in testng.xml cannot be typecasted to the corresponding test
method's parameter it will throw an error.******
******Your @Parameters do not have a corresponding value in testing.xml.You can solve
this situation by adding @optional annotation in the corresponding parameter in test
method.*****
******It is impossible to click iframe directly through xpath since it is an iframe.****

54. How Execute Autoit.exe?


Runtime.getRuntime().exec(scriptPath);

55. Disadvantages of pom


Automation Framework developed using POM approach is specific to the application.

56. How to pass headless browser in remotedriver? Executive on grid


Using DesiredCapabilities

57. Implicit wait


driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

58. Explicit Wait


wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))

59. how to test page loaded successfully


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

60. When do you use Java's @Override annotation?


If programmer makes any mistake such as wrong method name, wrong parameter types
while overriding, you would get a compile time error. As by using this annotation you instruct
compiler that you are overriding this method. If you don’t use the annotation then the sub
class method would behave as a new method (not the overriding method) in sub class.

61. Exract xpath of table cell/ Dynamic XPath- Done- Refer video again if need

WebElement table_element = driver.findElement(By.id("testTable"));


List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/
tbody/tr"));

List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());

62. How to handle window?


String handle= driver.getWindowHandle();//Return a string of alphanumeric window
handle
Set<String> handle= driver.getWindowHandles();//Return a set of window handle
driver.switchTo().window("windowName");

63. Handle ALert


Alert alert= driver.window.alert();
alert.accept();

64. TestNG Depedency Test


@Test
public void start() {
System.out.println("Starting the server");
}
@Test(dependsOnMethods = { "start" })
public void init() {
System.out.println("Initializing the data for processing!");
}

65. What is the use of getAttribute Command?


This method gets the value of the given attribute of the element. This accepts the String
as a parameter and returns a String value.
eg. WebElement element = driver.findElement(By.id("SubmitButton"));
String attValue = element.getAttribute("id"); //This will return "SubmitButton"

66. What are the test cases we cant automate by using Selenium?
Captcha
Bar code reader can't be tested.

67. Double click?


Action class
JavaScript
Robot class
68. css
Fast on IE compared to xpath
Do not support IE 8
Can not traverse in DOM
does not support the "contains" feature
69. Methids available in log4j
-Debug
-Error
-fatal
-Info
-warn
-trace
70. How to create an object for log4j
static Logger log = Logger.getLogger(log4jExample.class.getName());

71. Java serialization


an object can be represented as a sequence of bytes that includes the
object's data as well as information about the object's type and the types of
data stored in the object.

72. Why POM?


 A better approach to script maintenance
 Reuse
 We can separate operations and flows so easy to maintain and
reuse
 Object repository is independent of test cases
 Code becomes less and optimized

73. Which interface hashmap implements?


Map interface

75. What's the use of Firefox profile setting in selenium?

76. How to handle exception in testNG without using try catch block?
77..disadvantages of static block in java?
TestNG provides an option of tracing the exception handling of code. You
can test whether a code throws a desired exception or not. Here the
expectedExceptionsparameter is used along with the @Test annotation.
Eg. @Test(expectedExceptions = ArithmeticException.class)
78. What are the available Access modifiers in java?
79. Maven goals and lifecycle?
80. What are the methods are available in POI?
81. whats java serialization?

--------L&T questions-----

POM and Page factory


Find All
If you keep your objects in property file and element is not getting finby name and
property then where you will make changes
What is Hashmap?
How you iterate in hashmap?
Javascriptexecutor
Which method we use to scroll?
Why should not use Javascript executor?
Reverse the string
How many ways you can extract numerical digits from string? what are those?
How to switch from one frame to another and back to previous frame?
What are the API available to access data from xls file?
Other than POI and jxl what we can use to access data from xls file?
what are the ways to check object exist or not on webpage?
After clicking on button which is in frame opens another frame but it takes time to appear
how you will test?
Selenium webdriver exceptions
What is Immutable Objects?
How to check 200 response code?
What are the components of your framework?

Questions asked at BOA and Synechron


------------------------------------------------------

Count no of elements from Dropdown


Difference between findelement and findelements...if element not found then what will
happen in both cases?
Selenium supports many languages do you know how selenium works?
get text from elements from element without using gettext method
What is the meaning of Single forword slash and double forword slash
How to handle Alerts?
What are the problems you faced in automation?and how you handllled?
how to Run tests on other machine without using GRID?
Count number of frames on a page
Use of action class?
is it mandatory to use rounded brackets after catch block?
Difference between Verify and assert
How you handle exceptions?
What are the methods are available in apache POI to handle xls file?
Can I access static variable from another class?
In which case you used CSS but not xpath or any other locator?
Difference between StringBuilder and StringBuffer?

Java programmed--

Reverse the string


Extract number from alphanumeric string
palindrom
Change to caps first char after every space in a string

Rest questions were simple java questions

You might also like