Vous êtes sur la page 1sur 11

Selenium Questions 1

Selenium Mostly Asked Interview Questions


Q1. How to configure RC in eclipse
Download jar files from internet and include in eclipse projects.
Added inside project under eclipse.
Q2. What is Java Doc?
Documentation of selenium is known as java doc, it is downloaded with Jar files.
Go to javadoc folder and click on index.html.
Q3 what is default selenium class?
It has all the functions which are present in selenium interface its webdriver.
Q4. What is difference between throw and throws exception.
Throw:- we deliberately throws the exception
Throws :- we give the exception when same exception used many times
Q5. Finally block means?
Block which will always run
Q6. What is final keyword?
Final is a variable whose value cannot be changed.
Q7. How to store the entire link on a page using arrays? It may be dynamic.
There is a collection API which in build class called array list, it help in sto
ring dynamic increasing data structure.
Syntax :- arraylist<datatype> <object name> = new arraylist<data type>()
In selenium we can use when we have object in bulk.
Array list class do not have any final size.
Q8. Hash Table?
It is also dynamically growing data structure, it's an inbuilt class
Hashtable <string,string> table = new hashtable <string,string> ()
It always has a key value pair
Eg:-
Table.put(Key,Value)
There is no index there is a key and it should be unique.
One key can have only one value:-
Table.put(name,Aj)
Now
System.out.println(table.get(Name));
It will print Aj, hash table do not have index it will have key value.
In selenium it is used to store test data.
* So collection API has array and hash table.
Q9. How to create a array list inside a array list and hash table inside a hash
table?
Hastable<string,string> table1 = new hashtable <string,string>
Table1.put(City1,ja)
Table1.put(City2,fa)
Table1.put(City3,ma)
Hastable<string,string> table2 = new hashtable <string,string>
Table2.put(City1,3021)
Table2.put(City2,3221)
Table2.put(City3,3023)
Make them part of one table
Hastable <string,hashtable<string,string> > table = new hashtable <string,hashta
ble<string,string> >
Table.put(name,table1)
Table.put(zip,table2)
System.out.println(table.get(name).get(city2));
It will put:- fa
Q10. What is reflection API?
It is used to create hybrid frame work; it helps in calling the function whose n
ame is same as the name of variable
String x = Simplt text;
Now it will be done by:-
Method method = ReflectionAPI.class.getmethod(x, String.class);
Method.invoke(method, hellow);
Method is a inbuilt class in reflection API
And we have a function
Public static void samplttest (string x) {
System.out.println (In sample test +x);
Now above Reflection API.class.getmethod(x, String.class);
x will have value = sample text and get method will call the method getmethod sam
etext and String.class means method accept the value sting.
Method.invoke(method, hallow); here same text will be called and hallow is printed
.
So we can change the value of X and can call any function in it.
Selenium Question 2
Q1. Print title of each site in web title?
System.out.println (driver1.gettitle())
Driver. close will close the current browsers.
Driver. quit it will also do the same thing but it will close all the associate
d windows with it.
Driver.nevigate().to(http:bbc.com); this will also open the link, with navigate we
can use key press event like back and forward buttons, but we cannot do with ge
t.
Q2. what is a firefox profile ?
We want our own instance of firefox not the firefox used by every one though we
have common browser.
Close Fire fox with exit in file menu.
Go to run and give command firefox.exe profilemanager
A window will come Click on create profile and chose the folder whe you want to
save the profile.
Now start firefox, it will be brand new.
To open the same profile with selenium through eclipses.
ProfilesIni allprofiles = new ProfilesIni()
FireFoxProfile profiles = allprofiles.getprofile(teas)
ProfilesIni its an inbuld class that manages the profile, and it loads all the p
rofile.
FireFoxProfile profiles it will get the profile created with name Abhinav.
Q3. HTML unit Driver.
It never opens the browser and test.
WebDriver driver = new HtmlUnitDriver();
Q4. FireBug?
Its an addon to firefox, its like object spy in QTP. After installing firebug yo
u can install firepath it's a add-on over firefox, it show the Xpath of that butto
n or any field
What ever thing start with A it's a link in html.
Q5. To print all the values present in drop down?
Every thing comes under option box under a option tag of fire bug.
Webelement droplist = driver.findelement(by.xpath(Give Xpath))
Droplist.findelements(by.tagname(option));
It is returning a list so we have to write
List<WebElement> options = droplist.findelements(By.tagName(option));
System.out.println(option.size) // it will print the number of element
To print the element write a for loop and under it give
Webelemnt o = options.get(i);
System.out.println(o.gettext());
Or we can write
System.out.println(options.get(i).gettext())
We have value associated with each option
System.out.println(options.get(i).gettext() + ..+options.get(i).getattribute(Value);
Any thing on firebug with in tag <> is attribute.
Q6. How to handle radio buttons?
All radio buttons within a group will have same name but different value.
List<webelement> radio = driver.findelements(by.name(group1)
List will have all the radio buttons.
System.out.println(radio.get(0).getattribute(Value)+.+radio.get(0).getattribute(checke
d));
It will see is radio button checked or not.
Radio.get(0).click
It will click on first radio button.
Q7. Can we make our own Xpath?
Yes Ex:-
//*[@id='Email']
//input[@name = `Email']
//input[@id='Email' and @name = `Email']
Ctrl+shift+o :- all the imports come up
Q8. How to extract all the links from a web page?
List <webelement> alllinks = Driver.findelements(by.tagname(a))
`tagname(a))
As on firebug you can see all link tag name start with a.
System.out.println(alllinks.size()); // will print total number of link
For writing all the links use for loop
For (int i=0 ; i<alllinks.size();i++)
System.out.println(alllinks.get(i).gettext);
Q9. How to extract limited links not all the links.
So related links lie under a common Xpath ex:-
Webelement footer = driver.findelement(By.xpath(//*[@id='footer']))
List <webelemnts> footerlink = Footer.findelements(by.tagname(a);
For (int i=0 ; i<fotterlink.size();i++)
System.out.println(alllinks.get(i).gettext);
Q10. how to capture screenshorts with webdriver ?
File scrfile = ((takescreensort)driver).getscreensoretAs(outputtype.file))
Fileutil.copyfile(ScrFile, new file (C:\\tmp\\screensort.jpg));
Takescreensort is a class
Second command location is important.
Q1. How to store screen shorts of errors?
Best policy is first create a new folder for screen shorts
The function name is screen short
Public static void Takescreenshort(String finename) throws IOExceptions{
File scrFile = ((TakeScreenSort)driver).getScreenshortAs(OutputType.File);
FileUtils.copyFile(scrFile, new file(system.getproperty(User.dir)+\\screensort+fil
ename+.jpg));
Before the assertion call the function
Eg.
TestUtil.takescreensort(xpathKey);
Xpath or file name
Q2. System.err.println ()
It shows all system error.
Q3. How to email the reports?
Create a method which Zip any folder
It will have infolder and out folder and we have method for it in java.
Create a send mail function having all the send method parameters like port numb
er which accept username and password
Q4. Hybrid frame work Data driven frame work?
We have keywords in hybrid frame word.
In data driven frame work all data come from excel.
We have a core in it which do not have selenium code and we can implement frame
work for RC as well as webdriver.
1. Prepare test suits example :- TestSuites.xlsx
2. Prepare test cases and test data in excel file.
3. Introduce the run mode
4. Make eclipse package, logs,utilpackages,base package having base class,c
onfig contain all parameter like login file etc, xls package, package for listen
er will be used in test NG to report errors.
5. Put all the xls file in xls package.
6. Create a config file and OR properties files under config package.
Rules for making hybrid frame work:-
1. First write the primary file. Having information of all test suites
2. Name of suites xlxs should be same name as name of suit ID in suit.xlxs.
Create test cases for every test module in the separate so we have test case she
et, test step sheet, every test case have a run mode
In test case step keep the same test case ID as test case name.
Keep the test data sheet name same has test case.
Key word in test case step sheet, java code in selenium will use the keyword all
keyword have different impact and they are reusable.
We have generic keyword and applicant dependent keyword.
Generic which generic to any website.
3. Make A package for config and OR file also
4. Create a new package for logs file.
5. Implement the logic to read keywords and test cases in suites.
- Check the run mode of all the test suites if yes then execute the keyword for
the test case.
Q5. How selenium RC is different from IDE and web driver
IDE :- IDe exists on Mozilla tools option and we can start recoding from there,
here we can run only on mozilla . we can parameterize only using XML.
RC is available on many languages, 1.x old version, it has lot of issues like se
rver stating, we can onlt test web applications.
Webbdriver :- We can test mobile applications also, version (2.X)
Q6. How many ways we can dun RC code?
There are 2 ways
Q7. What is Selenium test case class and setup function.
It's a stand alone class, its has method like setup which takes up the URL and the
browser on which you want to open the URL.
Setup function will initialize default class and default class implement seleniu
m interface.
So setup function creates its object and gives reference to global field called
selenium.
Q8. Configure Web driver
Go to google enter download selenium.
Download it, we will have jar files.
Create a module in eclipses and add the external jars into the current project.
Q9. What is java doc?
Documentation related to selenium is known as java doc.
- Web driver is a interface in selenium.
Q10. How to add firefox driver in web driver.
Webdriver driver = new firefoxDriver();
Driver.get(http://gmail.com);
Same way you can add driver of internet explorer and other browsers.
Selenium Question 4
Q1. How to simulate key board button through selenium ?
In place of .click(username) write .sendkey(username)
.sendkey (Keys.Enter); // It will press enter.
Q2. How to attach a file or upload a file?
Selenium do not support mouse movement
Select the text box by its Xpath and type the picture path by send key
Example:- driver.findelement(by.xpath(///)).sendkey(picture path);
Q3. Selecting the Date ?
Just find its Xpath and click on it.
Q4. How to handle a dynamic table ?
List <WebElement> rows = table.findelements(by.tagname(tr);
System.out.println(total rows ->+rows.size());
As every row xpath is under tag name tr
Q5. What is webdriver.timeouts ?
Driver.manage().timeout().implicitewait(5, timeunit.seconds)
It will wait for 5 seconds after that it will throw an error if the value not fo
und.
Driver.manage().timeout().pageloadtimeout(10,timeunit.seconds)
It load the complete page before throwing any error, If the above page do not lo
ad in 10 second it will give an error. It is similar to synchronization time out
in QTP.
It give object of webdriver time out.
Q6. How to simulate back and front button on selenium ?
If we want to click on back button.
In place of get click on navigate, as get do not support back and forward button
s.
Driver.nevigate().to(http://gmail.com);
Driver.navigate().back();
Driver.nevigate().forward()
Q7. How to scroll your side bars ?
//You have to use event driven driver
Eventdriver driver = new eventFiringDriver
Scrolling is done through java script.
Driver.executescript(scroll(0,2000));
Q8. How to extract values?
Example :- set of itons(140)
And we need 140
String text = set of itons(140)
String temp [] = Linktext.split(\\();
Print temp[1]
It will show 140
So remove another bracket
Temp = temp[1].split(\\));
Print temp[0]
So now 140 will be printed.
Q9. Data Driven frame work ?
In which all the things are controlled by a excel file.
Config.property where we put all the properties in it and java code will read fr
om it.
Like
Testsitename
Browser
Screenshortpath
Create a new Xpath or or name file.
It will have all the xpath in it, we do it if we hard code it in selenium and de
veloper change it then we have to change every where here we have to change only
one place.
Create a package
Create a class
// inilitize the property file
Public static properties CONFIG = null;
Public static properties OR = null;
Public static webdriver dx = null;
Public static EventFiringwebdriver driver= null;
Public void initialize()
{
//here we have created a initialize mehod which will initialize config and OR
Config = new properties ();
Fileinputsteram fn = new fileinputstream(system.getproperty(user.dir)+//src//config
//config.properties);
CONFIG.load(fn)
// Now initialize OR. Properties
OR = new properties ();
Fileinputsteram fn = new fileinputstream(system.getproperty(user.dir)+//src//config
//OR.properties);
OR.load(fn)
//Now initialize the driver
If(CONFIG.getproperty(browser).equal(browsername){
Then initialize the driver with the browser.
// you need to implement event firing webdriver for mouse events etc
EventFiringWebDriver driver = new EventFiringWebDriver(driver)
// Now give webdriver implicit wait.
// it will give path of current project
}}
.. now use assertion of junit
// now create a class extending above base class
Eg :- in new test class
Public class login extend testbase{
Driver.get(CONFIG.getproperty(testsitename));
}
//so all the properties and driver object is from extended class
// Now create the separate function for all the common working like login. Which
will extend the calling class.
// used if there is some special character.
And what ever we are getting put in an array.
Q10. What is difference between assertion and error collector?
Assertion fails the script stop the execution
Error collector we can report all the errors
Selenium Question 5
Q1. How to identify object other than Xpath?
It is on the bases of ID.
driver.findelement(by.id(ID of link)).click
driver.findelement(by.testlink(ID of link)).click
driver.findelement(by.partiallinktext(Incomplete link)).click
driver.findelement(by.xpath(xpath)).sendkeys(Val)
driver.findelement(by.classname(xpath)).sendkeys(Val)
Class name should be unique and should be present.
Q2. Can we replace the start in Xpath ?
Yes :- * can be replaced with input which is a tag name.
Q3. How to handel a weblist ?
Ex:- dropdown
Driver.findelemet(by.Xpath(Xpath)).sendkey(Goa);
Q4. What is compound class name?
Class name having space in between and they are supported while creating Xpaths.
We can specify the text of the link in xpath
Eg:-
Driver.findelement(By.xpath(//a[test()='camera Accessories'])).click.
Q5. If two attribute have same href attribute then?
It will point to first occurrence of the hrif doc.
Q6. How to switch over to popup or tab window.
Set<string> windowsids = driver.getwindowhandles();
Iterator<string> iter = windowsids.iterator();
String tabbedwindowID = iter.next();
Driver.switchto().window(tabbedwindowID)
Q7. How to handle a certificate issue?
After creating firefox profile write these two lines :-
Profile.SetAcceptUntrestedCertificates(true);
Profile.SetAssumeUntrestedCertificatesIssuer(false);
These are standard line and they are from API, we will not get the error.
For IE :-
Driver.nevigate().to(javascript:document.getelementById(`overridelink').click
Q8. What happen if Xpath keep on changing?
Use some java scrip function
Eg:- Input[starts-with(@id, `hellow_'))
Q9. How to pause the execution of program for some time ?
Threed.sleep(1000L); // its 10 second
It is fine but problems come if we are clicking on a link and the page does not
appear with in 10 seconds or it comes up with in 2 seconds.
Driver.get () wait till the page is loaded
So the better way is put a global time out it the page is not visible in that ti
me it will throw an error.
Driver.manage.timeouts.implictlywait(10L, TimeUnit.Seconds)
Time unit is a inbuilt class in selenium.
If an element takes more time then 10 seconds then we can write thread. sleep or
alter the time out increasing implicitly time out.
Q10. How to handle java script alert messages with selenium.
Alert alt = Driver.swithchTo().alert();
Alt
We use accept: - it click on OK button
Alt.dismiss :- it will click on cancel button
Alt.get text :- It will get the text.
Selenium Question 6
Q1. What is the use of property file?
It is similar to object repository. For reading the value from properties file w
e create a object with class properties.
Properties prop = new properties();
Prop here help to get the contents from a properties file.
FileInputStream IP = new FileInputStream(Property file path)
Prop.load(ip)
System.out.println(prop.getproperty(name));
It will write the value in property file.
It helps to create loosely coupled frame work.
Q2. What is the use of system.getproperty(user.dir)?
It give us the current path of directory we are working on
Q3. What is POI API?
It is used to read excel files in java
We do this by right click on project and go to project properties, go to java bu
ild path, click on libraries tab.
Click on add external jar buttons and select the POI API Jar files.
Q4. While running a selenium we what to know what actually have happened if some
thing pass or fail?
So we need to generate the logs, add a jar file name log4J.
This jar contain lot of packages and classes, we are concern about log4j.propert
ies.
It contains the information about the log file we have to create, just specify t
he path.
To use this file under a class:- Create a object of the class present in log4js
Logger Application_LOGS = logger.getlogger(devpinologger)
APPLICATION_LOGS.debug(Starting);
APPLICATION_LOGS.debug(executing);
APPLICATION_LOGS.debug(ending);
This will write the logs.
Q5. What is role of Junit
Ex we have 4 selenium script , we have excel file, generate logs and generate lo
gs.
So we need a centralized controller so we use Junit or Test Ng.
For junt frame work.
Create a new project -> go to properties -> library and select Junit or add fro
m library.
Junit comes with eclipses.
Now cerate a new class and do not create any main function (as there is no main
function in Junit there are annotations. Junit annotations are known as @Test a
nd import junit files.
@test it's a predefined class in Junit.
Add some functions
We have Junit window which show have reports.
Write test word in front of every function, other wise Junit will not work fine
@before this function is call before calling any @test functions.
@before this function is call after calling any @test functions.
@beforeclass :- this will be the first function which will be called.
@ Afterclass :- this will be the last function which will be called.
@beforeclass, @ Afterclass functions should be static.
@Ignore on the top of any function, that function will not be called.
Assume.assumeTrue(False); will halt the execution of a test.
How to parameterize using Junit.
1. Write @RunWith (Paramatrized.class) on top of class you want to parametrize.
2. Declare some global variable, which will act as input doe any variable.
3. Build a constructor of the class so class can be initialized.
4. Add a annotation @parameters

Q6. Error Collector In Junit.
It's a in build class in Junit, help to report errors in Junit. Assertion are used
in it :- it see is any condition true or not.Eg assert.assertequal(Hellow,Hellow)
Draw back if assertion fail the code after assert will not be executed, code exe
cution fail., we can handle with try catch block
Assert.asserttrue (error message, 3>1)
Condition is false then only error message will be printed.
For reporting any error we create a object of class errorcollector and put @rule
on it
@rule
Public ErrorCollector = errcol = new errocollector()
Now on the catch block write
Catch (Throwable t)
{
errCol.adderror(t);
system.out.println(Error)
}
Now In junit error will be reported.
Q7. Batch running in selenium using Junit framework.
We user runners in junit , class is known as runner class
Create a class
Over it write
@Runwith(Suite.class)
@suiteclass{{
Logintest.class,
Paramatrized_test.class}}

Q8. Clicking on a button?
Webelement username_button = Driver.findelement (By.Xpath(Button Xpath))
username_button.click();
Q9. If we have multiple fields do we have to write every time Driver.findelement
.By.Xpath ?
NO
We can do
driver.findelement(By.Xpath(field Xpath).sendkey(xxx).
driver.findelement(By.Xpath(button Xpath).click().
Q10. Clear function?
To clear any text box.
Selenium Question 7
Q1. If a character is not present in sting and we try to get its index what it r
eturn?
-1
Q2. What split functions do in string class?
To split a string on the bases of space and returns a string array
String str = the money is here;
String temp[] = str.split( )
Temp[0] will have the
Temp[1] will have money
Now we split on the bases of is now:-
Temp[0] will have the money
Temp[1] will have here
Q3. Convert string to integer?
String x =100
Int i = Integer.parseInt(x);
Integer is a class and it has static function
Here Integer.parse only pass Integer
Vice verca
String z = string.valueof(i)
For Boolean
Boolean b= Boolean.valueof (true);

Vous aimerez peut-être aussi