100% found this document useful (1 vote)
419 views

Selenium Interview Questions - Chercher - Tech

The document discusses the history and naming of Selenium, how to exclude test methods in TestNG, how to check if an element exists on a page, what TestNG is and basic steps to write TestNG tests, TestNG annotations, how to create and use a testng.xml file, TestNG assertions, soft asserts in TestNG, hard asserts in TestNG, exception handling tests in TestNG, setting test priority in TestNG, running tests in parallel using TestNG, disabling and ignoring tests in TestNG, attributes of the @Test annotation, the time unit used in TestNG, and advantages of TestNG over JUnit.

Uploaded by

ANUSHA S G
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
100% found this document useful (1 vote)
419 views

Selenium Interview Questions - Chercher - Tech

The document discusses the history and naming of Selenium, how to exclude test methods in TestNG, how to check if an element exists on a page, what TestNG is and basic steps to write TestNG tests, TestNG annotations, how to create and use a testng.xml file, TestNG assertions, soft asserts in TestNG, hard asserts in TestNG, exception handling tests in TestNG, setting test priority in TestNG, running tests in parallel using TestNG, disabling and ignoring tests in TestNG, attributes of the @Test annotation, the time unit used in TestNG, and advantages of TestNG over JUnit.

Uploaded by

ANUSHA S G
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/ 8

Why did they Name as Selenium ?

Couple of years back we had only one automation giant which is QTP ( currently known as UFT ).
QTP was owned by company called Mercury, they were charging heavy for the QTP product.
After years a program was developed by Jason Huggins a programmer at ThoughtWorks (still we can
find couple of thought work pacakages in selenium webdriver if you have noticed), they wanted to
name the program as something which gives opposite meaning to QTP, later they gave name
Selenium.
Selenium is Chemical mineral which cures the wounds caused by Mercury.

How to exclude a particular test method from a test case execution?


We can exclude a particular testcase by adding the exclude tag in the testng.xml or by setting enabled
attribute to false
<classes>
<class name="TestCaseName">
<methods>
<exclude name="TestMethodNameToExclude"/>
</methods>
</class>
</classes>

Check If An Element Exists?


You may need to perform a action based on a specific web element being present on the web page.
You can use below code snippet to check if a element with id 'element-id' exists on web page.
if(driver.findElements(By.id("element-id")).size()!=0){
System.out.println("Element exists");
}else{
System.out.println("Element donot exists");
}

What is TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing
to integration testing.

Explain what are the basic steps required in writing TestNG tests?
1. Write down the business logic of your test and insert TestNG annotations in your code
2. In a build.xml or testing.xml, add the information about your test
3. Run TestNG

What are the annotations available in TestNG?


@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test
How to create and run testng.xml ?
In TestNG framework, we need to create testng.xml file to create and handle multiple test classes. We
do configure our test run, set test dependency, include or exclude any test, method, class or package
and set priority etc in the xml file.

What is the importance of testng.xml file?


In a Selenium TestNG project, we use testng.xml file to configure the complete test suite in a single
file. Some of the features are as follows testng.xml file allows to include or exclude the execution of
test methods and test groups
It allows to pass parameters to the test cases
Allows to add group dependencies
Allows to add priorities to the test cases
Allows to configure parallel execution of test cases
Allows to parameterize the test cases

What is TestNG Assert and list out common TestNG Assertions?


TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the
TestNG Assertions, we will consider a successful test only if it is completed the test run without
throwing any exception. Some of the common assertions supported by TestNG are
1. assertEqual(String actual,String expected)
2. assertEqual(String actual,String expected, String message)
3. assertEquals(boolean actual,boolean expected)
4. assertTrue(condition)
5. assertTrue(condition, message)
6. assertFalse(condition)
7. assertFalse(condition, message)

What is Soft Assert / Verify in TestNG?


Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails
and would continue with the next step after the assert statement.
If there is any exception and you want to throw it then you need to use assertAll() method as a last
statement in the @Test and test suite again continue with next @Test as it is.

What is Hard Assert in TestNG?


Hard Assert throws an AssertException immediately when an assert statement fails and test suite
continues with next @Test

What is exception test in TestNG?


TestNG gives an option for tracing the Exception handling of code. You can verify whether a code
throws the expected exception or not. The expected exception to validate while running the test case
is mentioned using the expectedExceptions attribute value along with @Test annotation.

How to set test case priority in TestNG?


We use priority attribute to the @Test annotations. In case priority is not set then the test scripts
execute in alphabetical order
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println("Test Case 1");
}
@Test(priority=1)
public void testCase2() {
system.out.println("Test Case 2");
}
}

How to run test cases in parallel using TestNG?


we can use “parallel᾿ attribute in testng.xml to accomplish parallel test execution in TestNG The
parallel attribute of suite tag can accept four values:
tests – TestNG will run all the methods in the same tag in the same thread, but each tag will be in a
separate thread. This allows you to group all your classes that are not thread safe in the same and
guarantee they will all run in the same thread while taking advantage of TestNG using as many threads
as possible to run your tests.

classes – TestNG will run all the methods in the same class in the same thread, but each class will be
run in a separate thread.

methods – TestNG will run all your test methods in separate threads. Dependent methods will also
run in separate threads but they will respect the order that you specified.

instances – TestNG will run all the methods in the same instance in the same thread, but two methods
on two different instances will be running in different threads..

the attribute thread-count allows you to specify how many threads should be allocated for this
execution.

<suite name="Regression" parallel="methods">

How to disable a test case in TestNG ?


To disable the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)

How to Ignore a test case in TestNG?


To ignore the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)

What are @Test attributes ?


@Test - Marks a class or a method as part of the test.
alwaysRun - If set to true, this test method will always be run even if it depends on a method that failed.
dataProvider - The name of the data provider for this test method.
dataProviderClass - The class where to look for the data provider. If not specified, the data provider will
be looked on the class of the current test method or one of its base classes. If this attribute is specified,
the data provider method needs to be static on the specified class.
dependsOnGroups - The list of groups this method depends on.
dependsOnMethods - The list of methods this method depends on.
description - The description for this method.
enabled - Whether methods on this class/method are enabled.
expectedExceptions - The list of exceptions that a test method is expected to throw. If no exception or a
different than one on this list is thrown, this test will be marked a failure.
groups - The list of groups this class/method belongs to.
invocationCount - The number of times this method should be invoked.
invocationTimeOut - The maximum number of milliseconds this test should take for the cumulated time
of all the invocation counts. This attribute will be ignored if invocationCount is not specified.
priority - The priority for this test method. Lower priorities will be scheduled first.
successPercentage - The percentage of success expected from this method
singleThreaded - If set to true, all the methods on this test class are guaranteed to run in the same thread,
even if the tests are currently being run with parallel="methods". This attribute can only be used at the
class level and it will be ignored if used at the method level. Note: this attribute used to be called
sequential (now deprecated).
timeOut - The maximum number of milliseconds this test should take.
threadPoolSize - The size of the thread pool for this method. The method will be invoked from multiple
threads as specified by invocationCount.
Note: this attribute is ignored if invocationCount is not specified.

What is the time unit we specify in test suites and test cases?
We specify the time unit in test suites and test cases is in milliseconds.

List out the advantages of TestNG over Junit?


Compare to JUnit annotations, TestNG are easy to understand
Unlike JUnit, TestNG does not require to declare @BeforeClass and @AfterClass
Method name constraint is not there in TestNG
TestNG allows you the grouping of test cases easily which is not possible in JUnit
TestNG supports following three additional setup: @Before/AfterSuite, @Before/AfterTest and
@Before/AfterGroup
TestNG does not need to extend any class
In TestNG, it is possible to run selenium test cases in parallel
Based on group TestNG allows you to execute the test cases
TestNG allows you to determine the dependent test cases; each test case is autonomous to other test
case.

Explain what is Time-Out test in TestNG?


The Time-Out test in TestNG is nothing but time allotted to perform unit testing. If the unit test fails
to finish in that specific time limit, TestNG will abandon further testing and mark it as a failed.

How to write regular expression in testng.xml file to search @Test methods containing
"product" keyword.
Regular expression to find @Test methods containing keyword "product" Is as bellow.
<include name=".*product.*"/>

Explain what is exception test?


TestNG gives option for tracing the Exception handling of code. You can test whether a code throws
the expected results or not. The expectedExceptions parameter is availed along with @Test
annotation.

Explain what is parametric testing?


Parameterized testing allows developers to execute the same test over and over again using different
values. In two different ways TestNG allows you to pass parameters directly to your test methods.
1. With testng.xml
2. With Data Providers
Explain how can you run the JUnit tests using TestNG?
You can run the JUnit tests using TestNG by
1. Placing JUnit library on the TestNG classpath, so it can locate and use JUnit classes
2. Change your test runner from JUnit to TestNG in Ant and then run TestNG in “mixed mode᾿ .
This will bring all your test in the same
3. This approach also enables you to convert your existing JUnit test to TestNG

What does @Test(invocationCount=?) and (threadPoolSize=?) indicates?


@Test (threadPoolSize=?): The threadPoolSize attributes tell TestNG to form a thread pool to run
the test method through multiple threads. With threadpool, the running time of the test method
reduces greatly.
@Test(invocationCount=?): The invocationcount tells how many times TestNG should run this test
method

Mention different ways in which you can produce reports for TestNG results?
There are two ways to produce a report with Test NG, they are
Listeners: For a listener class to implement, the class has to implement the org.testng./TestListener
interface. These classes are informed at runtime by TestNG when the test begins, finsishes, skips,
passes or fails.
Reporters: For a reporting class to implement, the class has to implement an org.testng/Reporter
interface. When the whole suite run ends, these classes are called. When called, the object consisting
the information of the whole test run is delivered to this class.

How to pass parameter with testng.xml file to use It In test case?


We can define parameter in testng.xml file using syntax like bellow.
<parameter name="browser" value="FFX" />
Here, name attribute defines parameter name and value defines value of that parameter. Then we can
use that parameter In selenium test case using bellow given syntax.
@Parameters ({"browser"})

Explain in what ways does TestNG allows you to specify dependencies?


TestNG allows you to specify dependencies in two ways
1. Using attributes dependsOnMethods in @Test annotations
2. Using attributes dependsOnGroups in @Test annotations

What is the default priority of test cases in TestNG?


The default priority of test when not specified is integer value 0. So, if we have one test case with
priority 1 and one without any priority then the test without any priority value will get executed first .

What is difference between @Factory and @DataProvider annotation?


@Factory method creates instances of test class and run all the test methods in that class with
different set of data.
Whereas, @DataProvider is bound to individual test methods and run the specific methods multiple
times.

How To Check If An Element Is Visible With selenium?


The above mentioned method may be good to check if a element exists on page.
However sometimes a element may be not visible, therefore you can not perform any action on it.
You can check whether an element is visible or not using below code.
WebElement element =driver.findElement(By.id("element-id"));
if(element instanceofRenderedWebElement) {
System.out.println("Element visible");
} else {
System.out.println("Element Not visible");
}

How to Wait For Element To Be Available?


The application may load some elements late and your script needs to stop for the element to be
available for next action.
You can perform this check using below code.
In below code, the script is going to wait maximum 30 seconds for the element to be available. Feel
free to change the maximum number per your application needs.
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("id123")));

How to Focus On A Input Element On Page ?


Doing focus on any element can be easily done by clicking the mouse on the required element.
However when you are using selenium you may need to use this workaround instead of mouse click
you can send some empty keys to a element you want to focus.
WebElementelement =driver.findElement(By.id("element-id"));
//Send empty message to element for setting focus on it.
element.sendKeys("");

How to Overwrite Current Input Value in editable field On Page?


The sendKeys method on WebElement class will append the value to existing value of element.
If you want to clear the old value. You can use clear() method.
WebElement element = driver.findElement(By.id("element-id"));
element.clear();
element.sendKeys("new input value");

How to Mouseover Action To Make Element Visible Then Click?


When you are dealing with highly interactive multi layered menu on a page you may find this useful.
In this scenario, an element is not visible unless you click on the menu bar.
So below code snippet will accomplish two steps of opening a menu and selecting a menu item easily.
Actions actions = new Actions(driver);
WebElement menuElement = driver.findElement(By.id("menu-element-id"));
actions.moveToElement(menuElement).moveToElement(driver.findElement(By.xpath("xpath-of-
menu-item-element"))).click();

How to Extract CSS Attribute Of An Element?


This can be really helpful for getting any CSS property of a web element.
For example, to get background color of an element use below snippet
String bgcolor = driver.findElement(By.id("id123")).getCssValue("background-color");
// and to get text color of an element use below snippet
String textColor = driver.findElement(By.id("id123")).getCssValue("color");

How to Find All Links On The Page?


A simple way to extract all links from a web page.
List<WebElement> link = driver.findElements(By.tagName("a"));
How do you check whether an element enabled or not ?, condition: there is no such attribute
as "disabled" in the element ?
Explanation : When there is no such attribute as disabled in element, the isEnabled() method from
selenium does not work.
Solution : There is some attribute which makes the element to be disabled so we have to find the
element and get the attribute using getAttribute() method then compare what is the value for enabled
and disabled. BAsed on this we can conclude whether the element is enabled or not.

Why do we write Webdriver driver = new FirefoxDriver(), why not SearchContext driver =
new FirefoxDriver() ?
Don't hurry to answer like, Webdriver is interface and FirefoxDriver is Class. This is right but you
need to understand the question first.
He is asking about SearchContext, which is parent interface of Webdriver, so the answer would be .
Yes, we can write like that because SearchContext is parent of all the Interfaces and classes present in
selenium.

Is it possible to automate captcha ?


Yes, we can automate the captcha but there is a limitation that we can automate our own captcha but
not others'
For example, a company has captcha in their website, so somebody has to check it but same time it is
not possible for manual tester to check all the captcha's.
So we have to automate the captcha in dev/qa environment by getting the captcha answer in some
attribute of the element, so based on that attribute we can enter the value to the text bar which accepts
captcha value.
We should remove this attribute while pushing the code to Live environment.

Testcase failed saying "ElementNotVisible", but when analyzed manually element is visible
? How to Handle it ?
There are couple of things which may cause this issue.
Element may not be visible in automation due to the speed of selenium.
If you closed a hidden division pop up, and tried to perform action, then there is a chance that hidden
division popup' animation wanot over which could cause this issue.
There is could be an another element which has same xpath or locator in some other page
Example : Consider you have a element which has xpath as //button[@id='abc'] on page X, by
clicking some tab on xpage navigates the user to Y page, Now there is an element on Y page which
have xpath same as //button[@id='abc'].
But when you launch your application, application may be directly landed on page Y. So with this
scenario, if you try to perform on element on Y page it could throw an Exception.
Step by step Solution :
First verify whether it is really any of the above scenario ?
Print number of element present with that xpath using findElements method
If there is only one element please follow program 1, If there is more than 1 element follow program
2.

Program 1 : Using Explicit wait (Wait for the element to be visible):


1. Open the url (please change according to your application).
2. Create object for WebdriverWait set wait time as 60 seconds.
WebDriverWait wait = new WebDriverWait(driver, 60 /*seconds*/);
3. Use visibilityOfElementLocated method present in Expected conditions class
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(buttonXpath)));
Complete Program 1 with Explicit wait (Wait for the element to be visible)
// PLEASE DO WRITE IMPORT STATEMENTS
// set the webdriver Wait as 60 seconds
WebDriverWait wait = new WebDriverWait(driver, 60 /*seconds*/);
String buttonXpath = "//button[@id='abc']";
// wait for the element to be visible, max wait time is 60 seconds
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(buttonXpath)));
// clicks the button which has xpath = //button[@id='abc']
driver.findElement(By.xpath(buttonXpath)).click();
Program 2 : Using findElements And IsDisplayed:
1. Open the url (please change according to your application).
2. Set implicitly wait for 1 minute
3. Find all the elements which matches the xpath and store them 4. iterate over the element we stored
5. verify if the element is displayed or not
6. Click element if displayed or ignore
7. Once element is clicked, break the loop.
Complete Program 2 : findElements And IsDisplayed:
// PLEASE DO WRITE IMPORT STATEMENTS
// open webpage
driver.get("https://www.google.com/");
String buttonXpath = "//button[@id='abc']";
// find all the elements with that xpath match
List elements = driver.findElements(By.xpath(buttonXpath));
// iterate over the elements
for (WebElement webElement : elements) {
// check whether element is displayed or not,
if (webElement.isDisplayed()) {
// if displayed click the element and break the loop.
webElement.click();
break;
}
}

Do implicit wait has any impact on findElements ?


Most of the time implicit wait will not work with findElements but only when there is no element for
the given locator then only implicit wait works from findElements.

You might also like