quest
Selenium
- Suppose we are using link test as locator, If in the screen page it is showing like "FREE DEMO" but when we inspect it, It shows "Free Demo". Then which one to pick?
Ans : Whatever appears in the screen we will select that, means FREE DEMO
- What if there are multiple links are associate with this partial link test then which will work.
Ans : If there appears multiple links with this partial link test then first link will be come into the picture. means it will be functional for that time.
- What is xpath ?
Ans : A query language which is used to find a node or set of nodes in XML/HTML documents.
- What are cross-browser testing ?
Ans : Cross browser testing involves comparing and analyzing the behavior of application under test in different browser environments And why we are doing that so the answer for that is, Cross browser testing helps to pinpointing browser-specific compatibility errors.
It helps ensure that you're not segregating a significant part of your target audience–simply because your website does not work on their browser-OS.
- What are some important testing metrics ?
Ans: Metrics decide the software’s quality and performance. Developers may utilize the appropriate software testing standards to enrich their productivity.
a. Test Cases Executed Percentage: It measures the status of the test cases executed for the entire application.
Percentage of test cases executed = (No of test cases executed / Total no of test cases written) x 100
b. Defect Density: It measures the number of defects found per line of code or module and evaluates the quality of the code.
The higher the software quality, the lower the defect density.
Defect Density = Total Defects / Size of the Module
c. Test Case Effectiveness: It measures the efficiency of test cases in identifying defects.
Test Case Effectiveness = (Defects Detected / Test Cases Run) x 100
d. Defect Leakage: It evaluates the percentage of defects that are left uncovered by the testing team but found by end users or customers.
Defect Leakage = (Defects Found Post-Testing / Defects Found Pre-Testing) x 100
e. Defect Removal Efficiency: It evaluates the effectiveness of the testing process in identifying defects throughout the SDLC.
Defect Removal Efficiency = (Defects Removed / Total Defects at Start) x 100
f. Test Coverage: It measures the extent to which the application’s source code, functionalities, or requirements are tested.
Test Coverage = (Tested Functionalities / Total Functionalities) x 100
6. What is acceptance testing? when we do it ?
Ans : Acceptance Testing is an important aspect of Software Testing, which guarantees that software aligns with user needs and business requirements.
A. User Acceptance Testing (UAT)
* User acceptance testing is used to determine whether the product is working for the user correctly.
* Specific requirements which are quite often used by the customers are primarily picked for testing purposes.
This is also termed as End-User Testing.
B. Business Acceptance Testing (BAT)
* BAT is used to determine whether the product meets the business goals and purposes or not.
* BAT mainly focuses on business profits which are quite challenging due to the changing market conditions and new technologies, so the current implementation may have to being changed which results in extra budgets.
C. Regulations Acceptance Testing (RAT)
* RAT is used to determine whether the product violates the rules and regulations that are defined by the government of the country where it is being released.
D. Alpha Testing
* Alpha testing is used to determine the product in the development testing environment by a specialized testers team usually called alpha testers.
E. Beta Testing
* Beta testing is used to assess the product by exposing it to the real end-users, typically called beta testers in their environment.
* Feedback is collected from the users and the defects are fixed. Also, this helps in enhancing the product to give a rich user experience.
7. What is getWindowHandle() and getWindowsHandels(). What are their return type ?
Ans : getWindowHandle() returns the window handle of currently focused window/tab.
Return type of getWindowHandle() is String.
getWindowHandles() returns all windows/tabs handles launched/opened by same driver instance including all parent and child window.
Return type of getWindowHandles() is Set<String>.
The return type is Set as window handle is always unique.
String currentwindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
Iterator<String> i = allWindows.iterator();
while(i.hasNext()){
String childwindow = i.next();
if(!childwindow.equalsIgnoreCase(currentWindow)){
driver.switchTo().window(childwindow);
System.out.println("The child window is "+childwindow);
} else {
System.out.println("There are no children");
}
}
8. What is the difference between Thread.sleep() & selenium.setSpeed() ?
Ans : Both will delay the speed of execution.
a. Thread.sleep ():
It will stop the current (java) thread for the specified period of time. Its done only once
• It takes a single argument in integer format
Ex: thread.sleep(2000)- It will wait for 2 seconds
• It waits only once at the command given at sleep
b. SetSpeed (): For a specific amount of time it will stop the execution for every selenium command.
• It takes a single argument in integer format
Ex: selenium.setSpeed(“2000”)- It will wait for 2 seconds
• Runs each command after setSpeed delay by the number of milliseconds mentioned in set Speed
10. How you select testcases for regression testing.
Ans : Based on the following factors we can decide which testcases we have to select for the regression testing.
a. Test cases that yield bugs frequently
* Over the production cycle, one can identify test cases that fail more frequently.
* The areas of the software that these test cases cover are often fragile and usually malfunction after a change.
* These cases need to be prioritized and added to the regression test suite.
b. Test cases that cover business-critical functionalities
* Many parts of the software undergo frequent changes.
* These parts are more susceptible to defects.
* So, you should include them in your regression suite.
* Moreover, include test cases for functionalities that have recently changed.
c. Integration test cases
* In practice, integration tests are in a separate module.
* But it’s critical to include them in the regression suite too, which will ensure no last-minute changes disrupt the flow between different modules.
d. Field validation test cases
* These are negative test cases that cover field validations.
* Mandatory fields in a form need to be filled, without which users cannot move to the next stage.
e. Complex test cases
* High and medium priority test cases should be a part of every regression testing sprint, while low priority cases run only once before the final release.
11. Why the test cases review is required and who all are involved ?
Ans : The following are some of the test case review techniques,
a. Self-Review
* As the name suggests, self-review is done by the testers who create the test cases.
* By looking at the Software Requirement Specification (SRS) or Functional Requirement Document (FRD), they can check if all requirements are met.
b. Peer Review
* Peer review is done by other testers who are not much familiar with the application under test and have not created the test cases.
* It is also called the Maker and Checker review.
c. Supervisory Review
* Supervisory review is done by a test lead or test manager who is higher in rank than the tester who created the test cases and has a broad knowledge of the requirements and application under test.
12. How we can select other options present when we so the right click and at the time a lot of option is coming in one of the dialog box ?
Ans : a. Using Action and Robot class
Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
WebElement xx = driver.findElement(By.linkText("your element"));
Actions action = new Actions(driver);
System.out.println("To open new tab");
action.contextClick(xx).sendKeys(Keys.ARROW_DOWN).
sendKeys(Keys.ENTER).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
b. Using Action Class Only :
Actions action = new Actions(driver);
//Hold left shift and press F10
action.MoveToElement(element).DoubleClick().KeyDown(Keys.LeftShift)
.SendKeys(Keys.F10).KeyUp(Keys.LeftShift).Build().Perform();
13. Is there any different class used to handle the dropdown in spite of select class.
Ans :
1: By using Action Class
In Selenium Action class is used for handling keyboard and mouse events.
Example: Launch the application and click on desired option
WebElement dd= driver.findElement(By.xpath("//loc));
Action a = new Action(driver);
a.moveToElement(dd).click().build.(perform);
String opt= "option";
WebElement elem = driver.findElement(By.xpath+opt);
elem.click();
Action class in selenium can be used by importing import org.openqa.selenium.interactions.Actions package.
2: By using SendKeys
For the above used application we can use sendkeys() method to select an option
from dropdown by passing the elements value in send keys as shown in below example
dr.findElement(By.xpath("/loc")).sendKeys("opt");
3: By using JavaScript Executor class
In Selenium WebDriver JavaScript is executed with the help of an interface called JavaScript Executor.
WebElement dd = driver.findElement(By.xath("//loc"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='option'",dd);
JavaScript Executor in selenium can be used by importing import org.openqa.selenium.JavascriptExecutor package.
4: By creating custom Locator
We have to create custom locator and then handle the dropdown
dr.findElement(By.xpath ="//loc").click();
String opt = "";
WebElement dd = dr.findElement(By.xpath("//loc");
dd.click();
15. What is synchronization (waits) ?
Ans : Let’s say AUT and the testing tool has their speed.
Sometimes the Testing tool may be faster, and the AUT takes some time
for the page to load or for web elements to be present on the webpage.
In this case, the Testing tool may not find some aspects since its speed is faster than the AUT.
So, now the overall test fails.
AUT and the Testing tool should have the same working speed to overcome this distress.
Synchronisation brings the AUT and the Testing tool’s speed in sync.
It matches the speed of the application, and in some cases, it also waits for specific conditions.
Now, errors like ‘ElementNotVisible’ and ‘NoSuchElement’ may not arise.
a. Implicit Wait :
Implicit Wait in Selenium is a global wait that applies to all elements in the script.
It sets a maximum wait time for any element to become available before interaction.
If the element appears within the specified time, the script continues;
otherwise, it raises a TimeoutException, NoSuchElementException.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
b. Explicit Wait :
Explicit Wait in Selenium is a more granular approach that allows you to wait for a specific condition or element.
Explicit waits are applied to individual elements and provide better control and precision.
It often uses the WebDriverWait class and expected conditions to define custom waiting criteria.
Explicit waits are useful for efficiently handling dynamic web elements with different load times.
"TimeoutException"
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));
c. Fluent Wait :
Fluent Wait in Selenium allows one to wait for a specific condition to be met with a custom frequency of checking the condition.
Fluent waits are particularly useful when dealing with elements that may take varying times to load or change state.
This wait is created using the FluentWait class and configured with options like timeout, polling frequency, and exceptions to ignore.
"TimeoutException"
Wait<WebDriver> fluentWait =
new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(60))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement webElement =
fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.id("exampleId")));
d. PageLoadTimeout :
This wait is used for Web browser page load synchronisation.
Sometimes when the page load takes more time than the web driver’s speed,
the web driver throws TimeOutException. For the situation to get better, PageLoadTime is used.
16. Difference Between Action and Actions.
Ans :
Action (Interface):
-> Action is an interface that represents a single user interaction or behavior, such as a click or key Press.
-> It is used to execute a single action (e.g. , single perform() call on a built interaction )
Eg: Action action = new Actions(driver).moveTOElement(element).click().build();
action.perform();
* Here, Action is the result of calling build() on an Actions object, representing the sequence of user interactions as a single action.
Actions (Class)
-> Actions is a class in selenium that provides methods to build complex user interactions or
chains of actions, like dragAndDrop, multipleClick, or keyboard inputs.
-> It is a utility class that create a sequence of actions that can be executed as a unit.
-> Common methods of actions class are : moveToElement(),doubleClick(),dragAndDrop(),keyDown(),keyUp() etc.
Eg : Actions action = new actions(driver);
actions.moveToElement(element).click().perform();
Java
- What is Legacy Class in Java ?
Ans : In the past decade, the Collection framework didn't include in Java.
In the early version of Java, we have several classes and interfaces which allow us to store objects.
The classes and interfaces that formed the collections framework in the older version of Java are known as Legacy classes.
All the legacy classes are synchronized. The java.util package defines the following legacy classes:
1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
a. Vector :
* Vector is a special type of ArrayList that defines a dynamic array.
* ArrayList is not synchronized while vector is synchronized.
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{
System.out.println(data.nextElement());
}
}
b. Hashtable Class :
* The Hashtable class is similar to HashMap.
* It also contains the data into key/value pairs.
* It doesn't allow to enter any null key and value because it is synchronized.
public static void main(String args[])
{
Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{
Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
}
}
c. Properties Class :
* Properties class extends Hashtable class to maintain the list of values.
* The list has both the key and the value of type string.
* The main difference between the Hashtable and Properties class is that in Hashtable.
* We cannot set a default value so that we can use it when no value is associated with a certain key.
* But in the Properties class, we can set the default value.
public static void main(String[] args)
{
Properties prop_data = new Properties();
prop_data.put("India", "Movies.");
prop_data.put("United State", "Nobel Laureates and Getting Killed by Lawnmowers.");
prop_data.put("Pakistan", "Field Hockey.");
prop_data.put("China", "CO2 Emissions and Renewable Energy.");
prop_data.put("Sri Lanka", "Cinnamon.");
Set< ?> set_data = prop_data.keySet();
for(Object obj: set_data)
{
System.out.println(obj+" is famous for "+ prop_data.getProperty((String)obj));
}
}
d. Stack Class :
* class extends Vector class, which follows the LIFO(LAST IN FIRST OUT) principal for its elements.
public static void main(String args[]) {
Stack stack = new Stack();
stack.push("Emma");
stack.push("Adele");
stack.push("Aria");
stack.push("Ally");
stack.push("Paul");
Enumeration enum1 = stack.elements();
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
stack.pop();
stack.pop();
stack.pop();
System.out.println("\nAfter removing three elements from stack");
Enumeration enum2 = stack.elements();
while(enum2.hasMoreElements())
System.out.print(enum2.nextElement()+" ");
}
e. Dictionary Class
* The Dictionary class operates much like Map and represents the key/value storage repository.
* The Dictionary class is an abstract class that stores the data into the key/value pair.
public static void main(String[] args) {
// Initializing Dictionary object
Dictionary student = new Hashtable();
// Using put() method to add elements
student.put("101", "Emma");
student.put("102", "Adele");
student.put("103", "Aria");
student.put("104", "Ally");
student.put("105", "Paul");
//Using the elements() method
for (Enumeration enum1 = student.elements(); enum1.hasMoreElements();)
{
System.out.println("The data present in the dictionary : " + enum1.nextElement());
}
// Using the get() method
System.out.println("\nName of the student 101 : " + student.get("101"));
System.out.println("Name of the student 102 : " + student.get("102"));
//Using the isEmpty() method
System.out.println("\n Is student dictionary empty? : " + student.isEmpty() + "\n");
// Using the keys() method
for (Enumeration enum2 = student.keys(); enum2.hasMoreElements();)
{
System.out.println("Ids of students: " + enum2.nextElement());
}
// Using the remove() method
System.out.println("\nDelete : " + student.remove("103"));
System.out.println("The name of the deleted student : " + student.get("123"));
System.out.println("\nThe size of the student dictionary is : " + student.size());
}
Q2. What are cursor ?
Ans : a. Iterator:
* It is a universal cursor that can be used with any collection class.
* It allows you to traverse the collection in a forward direction, and it supports the removal of elements during iteration.
public void cursorTestIterator() {
List<String> names = new ArrayList<>();
names.add("Galu");
names.add("Shree");
names.add("Gugi");
names.add("Koko");
System.out.println("size of name list ->" + names.size());
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
b. ListIterator:
* This cursor is specific to List implementations (like ArrayList and LinkedList).
* It extends the capabilities of the Iterator by allowing bidirectional traversal (both forward and backward).
public void ListIteratorExample() {
List<String> names = new ArrayList<>();
names.add("Galu");
names.add("Shree");
names.add("Gugi");
names.add("Koko");
System.out.println("name list " + names.size());
ListIterator<String> listIterator = names.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("************hasPrevious*************");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
` c. Enumeration:
* Although not a part of the Java Collections Framework, Enumeration is an older cursor interface present in legacy classes like Vector and Hashtable.
* It allows forward traversal of elements.
public void EnumerationExample() {
Vector<String> names = new Vector<>();
names.add("Galu");
names.add("Shree");
names.add("Gugi");
names.add("Koko");
System.out.println("name list " + names.size());
Enumeration<String> elements = names.elements();
while (elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
Q3. What if final keyword assigned to the varibales, methods and class ?
Ans :
Variable : If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Methods : If you make any method as final, you cannot override it.
You will get compile time Error.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
class : If you make any class as final, you cannot extend it.
You will get compile time Error.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Q4. What are the difference between class and object ?
Ans : Classes are used to define the structure and behavior of objects, while objects are used to represent specific entities in a program.
Classes :
* A class is a blueprint for declaring and creating objects.
* Memory is not allocated to classes. Classes have no physical existence.
* You can declare a class only once.
Object :
* An object is a class instance that allows programmers to use variables and methods from inside the class.
* When objects are created, memory is allocated to them in the heap memory.
* A class can be used to create many objects. But all objects are different to each other.
Q2. What is clean Code ?
Ans : Clean Code is code that's easy to read, maintain, understand for developers and other teams while improving the quality of their software through structure and consistency with performance demands.
Q3. When to use abstract class and when to use interface?
Ans : Abstract Class :
-> Abstract class is a class in java That cannot be instantiated directly, means we cannot create object of the abstract class.
-> It includes both abstract methods(method without function) as well as concrete methods.
-> It is used as a blueprint for creating a subclass
-> To use this abstract class in any class we use extends method
Example
abstract class Animal
{
abstract void makeSound();
void sleep()
{ System.out.println("sleeping"); }
}
public class Dog extends Animal
{
@override
void makeSound()
{ System.out.prinln("Bark"); }
}
public class main
{
public static void main(String [] args)
{
Animal
}
}
Interface :
-> An interface in java is a blueprint for a class that contains only abstract methods(prior to java 8)
-> Starting from java 8 , interface can also include default and static methods.
-> Fields are implicitly public, static and Final.
-> It is used when you want to define a contract or behavior that multiple classes should implement then we use interface.
-> to use interface we use implements
Example :
interface Animal
{
void makeSound();
}
class Dog implements Animal
{
@override
public void makeSound()
{ System.out.println("Bark");}
}
public class Main
{
public static void main(String [] args)
{
Animal dog = new Dog();
dog.makeSound();
}
}
Q4. Why can’t we create the framework with all static methods?
Ans :
Using static methods limits reusability. For instance, if you need similar functionality in another class, you would have to duplicate or call the static method, which reduce the modularity.
POM works by creating instances of page classes. if all the methods were static, you would lose the advantage of encapsulation web element locators and methods within the page class object.
Q5. Can you explain what wrapper classes are in Java and why they are used?
Q6. How do you create a custom exception in Java, and in what scenarios would you use one?
Q7. How can you make an ArrayList synchronized in Java?
Q8. Can you explain the differences between Comparator and Comparable in Java, and when you would use each?
Q9. How would you convert an ArrayList to an array in Java?
testNG
Q1. What are testNG Listners.
Ans : Listener is defined as interface that modifies the default TestNG’s behavior.
As the name suggests Listeners “listen” to the event defined in the selenium script and behave accordingly.
It allows customizing TestNG reports or logs.
Type of iTEstListener :
OnStart- OnStart method is called when any Test starts.
onTestSuccess- onTestSuccess method is called on the success of any Test.
onTestFailure- onTestFailure method is called on the failure of any Test.
onTestSkipped- onTestSkipped method is called on skipped of any Test.
onTestFailedButWithinSuccessPercentage- method is called each time Test fails but is within success percentage.
onFinish- onFinish method is called after all Tests are executed.
Step 1 : we create a listner class and implements it with ITestListener
// When Test case get passed, this method is called.
@Override
public void onTestSuccess(ITestResult Result)
{
System.out.println("The name of the testcase passed is :"+Result.getName());
}
Step 2 : if we want to use in one specific test
then we can use the annotations like.
@Listeners(packageName.className.class)
3. If we want to use it for multiple classes then we can use it directly in the testNG.xml file
<listeners>
<listeners class-name="package_name.className">
</listeners>
Q2. What is DataProvider in testNG and how we use them ?
Ans : DataProvider in TestNG is a powerful feature that facilitates data-driven testing in Selenium.
It allows you to run the same test method multiple times with different sets of data, enhancing test coverage and efficiency.
A data provider method in TestNG is annotated with @DataProvider.
This method should return an Object[][].
There are two ways through which we can pass the data in any particular testcases :
1. First one is through the DataProvider
2. Through passing the value directly to the testNG.xml file.
import org.testng.Assert;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DProvider {
@DataProvider (name = "data-provider")
public Object[][] dpMethod (Method m){
switch (m.getName()) {
case "Sum":
return new Object[][] {{2, 3 , 5}, {5, 7, 9}};
case "Diff":
return new Object[][] {{2, 3, -1}, {5, 7, -2}};
}
return null;
}
@Test (dataProvider = "data-provider")
public void Sum (int a, int b, int result) {
int sum = a + b;
Assert.assertEquals(result, sum);
}
@Test (dataProvider = "data-provider")
public void Diff (int a, int b, int result) {
int diff = a - b;
Assert.assertEquals(result, diff);}}
* If the tester has not specified the name of the dataprovider,
* then the method name becomes the dataprovider name by default.
* TestNG dataprovider returns a 2d list of objects.
//testng.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "productSearchSuite">
<test name = "testPencilSkirt">
<parameter name = "productName" value="pencil skirt"/>
<parameter name = "shouldExist" value="true"/>
<classes>
<classname = "sampleTestNGPackage.TestProductSearch" />
</classes>
</test>
<test name = "testBackpack">
<parameter name = "browserName" value="backpack"/>
<parameter name = "shouldExist" value="true"/>
<classes>
<classname = "sampleTestNGPackage.TestProductSearch" />
</classes>
</test>
</suite>
Q3. Structure of TestNG?
Ans :
SomeQuestions
Answers
- How to take screenshot in selenium?
Ans:
a. we are creating a variable where we store the name of the image file.
b. Then we will create a file referance variable where we Use the ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE);
c. Then in try catch we will run the code FileUtils.copyFile that take two parameter the thr file referance variable amd a new FIle(image filename)
public static takeScreenshot(WebDriver driver, String FileCases)
{
String screenshotFileName = System.getProperty("User.dir")+"//Screenshots//"+FileCases+".jpg";
File srcFile = ((TakeScreenshot) driver).getScreenshotAs(OutputType.FILE);
try()
{
FileUtils.copyFile(srcFile,new File(screenshotFileName));
}catch(IOException e)
{
e.printStackTrace();
}
}
What is javaScrptExecutor ?
Ans : JavaScriptExecutor is an interface provided by Selenium that helps in executing JavaScript commands.
This interface provides methods to run JavaScript on the selected window or the current web page.
It provides two methods
a. executeScript():
b. executeScript():
Traditionally, to locate a WebElement, we use different Selenium locators such as ID, Name, CSS Selector, XPath, etc.
If these locators do not work, or you are handling a tricky XPath, in such cases,
JavaScriptExecutor helps to perform the desired operation on the WebElement.
What is Enum ?
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
}
When we are looping through the Enum we use
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
What is action class and what is its capability ?
Ans :
Actions class is an ability provided by Selenium for handling keyboard and mouse events.
In Selenium WebDriver, handling these events includes operations such as drag and drop in Selenium,
clicking on multiple elements with the control key, among others
Mouse Actions in Selenium:
doubleClick(): Performs double click on the element
clickAndHold(): Performs long click on the mouse without releasing it
dragAndDrop(): Drags the element from one point and drops to another
moveToElement(): Shifts the mouse pointer to the center of the element
contextClick(): Performs right-click on the mouse
Keyboard Actions in Selenium:
sendKeys(): Sends a series of keys to the element
keyUp(): Performs key release
keyDown(): Performs keypress without release
Selenium
Selenium Question
-
What are the latest feature which in available in the Selenium 4.X ?
-
How many ways we can create a drag and drop?
Ans :
1. Using Action Class
a. Using dragAndDrop()
Actions actions = new Actions(driver);
actions.dragAndDrop(source, destination).perform();b. Using clickAndHold() and moveToElement() Actions actions = new Actions(driver); actions.clickAndHold(source).moveToElement(target).release().bulid().perform(); 2. Using Robot Class a.
-
What build and perform in action library. what is action class simple class, abstract class or interface ?
Ans :
1. build() :
a. Build() method compiles multiple actions into a single, executable sequence.
b. It allows you to group multiple actions into one chain without executing then immediately.
c. The purpose of bild() method is to prepare a chain of actions to be executed.
d. When we need to create a complex sequence of actions then we use build.2. perform() : a. The perform() method executes the compiled sequence of actions. b. It can be called directly on an action chain or after calling build(). c.Executes the actions prepared in the chain.
-
Approach for writing the testcases for the Add to cart feature ?
Ans : Test Scenarios
1. Add single item to the cart and verify.
2. Add multiple quantities of the same item and verify.
3. Add different item to the cart and verify the total.
4. Try adding the out-of-Stock product and verify the error message.
5. Add one item then perform Log out and Login Function and Check that the item is available in the cart or not.
6. Remove item from the cart and verify the total cart value.
7. test add to cart in different browser.
Test Approach
1. Use automation testing tool like selenium.
2. Identify product element and cart control.
3. Assert cart total, item count, and message.
5. How to write test cases for a certain functionality.
Ans : 1. First step is we understand the flow of that functionality by doing manually which we want to automate so that we know the behavior.
Selenium Scenario Based
Q1. How to generate reports if we don’t have permission to use any external package for the report? We also can’t use HTML reports generated by TestNG.
Ans :
Approach 1 : Generate a custom text report.
Approach 2 : Generate a custom excel report.
Approach 3 : Generate log as a report.
Q2. How to rerun failed test cases apart from the failed test report
Ans :
Approach 1 : Using IRetryAnalyzer
Approach 2 : Using TestNG ITestListener
Approach 3 : Create a separate Failed test Suite.
Q3. Not able to click the element even though it’s visible clearly ?
Ans : It might be Due to some of the reasons :
a. Element overlapping or covered.
b. JavaScript or Animation Delay.
c. Incorrect element locators or Stale elements references
d. Element outside the viewport
Solutions for that :
a. Use JavaScriptExecutor to click.
b. Scroll into view before clicking.
c. wait for element to be clickable.
d. Handle overlapping element.
e. Retry clicking multiple time.
f. verify the locator accuracy.
Q4. What is test Data and How to store the test data.
Ans : Test Data refers to the input values, parameter and configuration used to execute test cases and verify the application behavior against expected outcomes. It is critical for testing functionality, performance and reliability of the software.
How to store data
1. Hardcoded in Test Script
2. properties file
3. Excel files
4. Json File
Small and simple datasets : Properties or Json File
Large datasets : Excel file
Structured hierarchical data : Json file.
Q5. Handel Cookies in Selenium
Ans : In simple terms, a cookie is a packet of data received by your machine and sent back to the server without being altered or changed.
Website owners (e.g., online shopping portals) use cookies to keep a tab on your shopping cart while browsing the site. Without the presence of cookies, your shopping cart might become empty (or the item count would reset to zero) each time you open up a new link on the site.
Here are the major functions of website cookies:
Tracking the browsing activity of the user.
Remembering the login details of the user.
Tracking the visitor count in a website further helps the website owners identify their unique visitors every day.
Set<Cookie> cookiesList = driver.manage().getCookies();
for(Cookie getcookies :cookiesList) {
System.out.println(getcookies);
}
Functions available for handling cookies in the selenium.
a. getCookies() : It returns the list of all the cookies
b. getCookieNamed(“Name of Cookie”) : It returns the cookie that matches the name specified as the argument
c. addCookie(“Cookie”) : addCookie(“Cookie”)
d. deleteCookie(“Cookie”) :
e. deleteCookieName(“Name of Cookie”)
Q6 . How to handel JavaScript Alerts. How many types of javascript Alerts are there ?
Ans : Alert in Selenium is a message/notification box that notifies the user about some
information or asks for permission to perform a certain kind of operation.
There are three types of alerts :
1. Simple Alert : That provides some message along with the "OK" button.
2. Prompt Alert : This alert will ask the user to input the required information to complete the task.
3. Confirmation Alert : This alert is basically used for the confirmation of some tasks.
For Example: Do you wish to continue a particular task? Yes or No?
Functionalities that we can perform with alerts.
a. dismiss() : This method is used when the ‘Cancel’ button is clicked in the alert box.
driver.switchTo().alert().dismiss();
b. accept(): This method is used to click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();
c. getText(): This method is used to capture the alert message.
driver.switchTo().alert().getText();
d. sendKeys(String stringToSend): This method is used to send data to the alert box.
driver.switchTo().alert().sendKeys("Text");
Q7. What are the different types of popup ?
Ans: There are few types of popup
1. Alert
2. prompt
3. Confirm
4. Browser popup : It includes os- level dialogs (e.g., FIle uploads, authentications)
For the we use Robot Class.
Q8. How many ways we can perform scroll by action?
Ans :
There are various way through which we can perform the scroll by actions :
1. Using JavaScriptExecutor :
a. Scroll by Specific Amount(x,y)
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
b. Scroll to a specific Element :
javascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);",element);
2. Using Action Class :
a. moveToElement(elem)
Actions actions = new Actions(driver);
actions.moveToElement(element).perform();
3. Using Robot Class :
a. Using keyboards keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
Q9. Can we have the @test with same priority as well as the negative priority value,
And what is the default value of the test priority.
Ans :
Default value of the test priority is 0.
Yes we can use negative value for the test priority.
the lesser the priority that earlt that testcases will be executed.
Q10. What are the mrthods present in the Navigation Commands.
Ans :
1. to() Command
dr.navigate.to(url);
2. back() command
dr.navigate.back();
3. forward() command
dr.navigate.forward();
4. refresh() command
dr.navigate.refresh();
Zephyr
- Create Release : (Version)
- Create Components : (SignIn, SingUp, Transaction)
- Epic is the biggest issue type we can create
create epic of Login Window - Create stories (Create requirements) In this we update the description by adding the scenarios in that.
then we link that story with the Components, Release and epic.
For Importing the testcases using excel file for that
the column name must be in proper format and must be in case Sensitive form.
Zephyr-zephyr Squad - import tests
Then after uploading the excel file we have to choose from which row we have map, what is the delimiter
and next we have to map the column name with the required component.
In Planning and Execution section :
we have cycle summary :
Defect will be created in the test step level.
Agile
- What is Burn Up and burn Down chart in agile ?
Ans :
Burn-up chart
Shows the amount of work that has been completed and the total project work. Burn-up charts are good for presenting project progress to the same audience on a regular basis. They can also help identify scope creep, which is when a project's scope increases.
Burn-down chart
Shows the amount of work remaining and the time frame to finish the work. Burn-down charts are good for helping teams focus on what work is left and encouraging accountability for the project. They can also help identify gaps between the ideal and actual completion rate.
Questions
https://www.youtube.com/watch?v=pg00DjXF3NM
-
Where did we store the screenshot.
-
Every time the screenshot will be deleted or we keep for the future reference.
-
How you use Jenkins in the project,
-
How much test coverage is good
-
How to handed JavaScript pop up.
-
How to handle JavaScript parent child popups
-
JavaScript executor Scroll by
-
How to invoke the testNG Listener
-
How we will utilize the listener with @test
-
Can we have the @test with same priority as well as the negative priority value. And what is the default value of the test priority.
-
Benefits of maven in place of java
-
Action Class and its capability
-
Why we are using the try and catch, is there any real life use (Some time it is beyond our control so we not try to fix that exception)
-
where try and catch you have used in the framework
-
Types of Locators
-
assertation methods in the assertion classes
-
Use of the collection framework in the test framework.
-
Types of waits and what if we not implement it.
-
How many parameters we have in the webDriver wait, and what are the exception we will get if any error found in these waits class. and their by default waits time.
-
What are the steps are required to fetch the value from the excel file. With code implementation. What exception we will get in this case
-
Types of annotation are in testNG
-
What are the steps involved in the taking screenshot in selenium, What will be its parameter of the takeScreenshot method. How we can take screenshot of different classes.
-
What is parallel testing and what is its importance.
-
What is synchronization (waits)
-
Structure of the testNG classes.
-
What is the reporter class
-
What is the select class and its methods available in that class.
-
Different parameter in @test like priority, invocation, Enabled
-
Is there any different class used to handle the dropdown in spite of select class.
-
What is robot class.
-
How we can select other options present when we so the right click and at the time a lot of option is coming in one of the dialog box.
-
Disadvantage of the selenium.
-
Data Provider annotation and its use.
-
getwindoHandel and getwindoHandels difference and its uses with code
-
Methods present in the navigate.
-
How can we give both the priority and the invocation to any of the @test annotation
-
Reporter class in the testNG
-
Various ways to click a link.
-
How to double click
Scenarios Based
- If we are doing the registration then what types of assertion we have to perform.
- Create a test script where you have to open the amazon website and search for 10 different things in one by one go.
- How we can perform the right click on any page.
- How to handle dropdown with keys
- Is it necessary to use the option retry again
- Is it really require to take screenshot and store it for the feature reference.
- When we are using the maven and the testNG which file we run to execute the testcases either the testNG.xml or the pom.xml why
- How parallel testing can be achieved using the selenium and its advantage.
- Refresh the page
- How to run the testcases in headless mode
- How to find out the brokens links in a given URL
- Presence of any component or say element present in any particular page.
- What if we not use assertation in the selenium, what will happen.
- How you have used the smoke and sanity testing in your project
- Your contributions to the project. Means earlier the test coverage is 45 % now because of my contribution the test coverage become 52 %
- How you have managed the negative test cases , which helps to find the corner cases,
https://www.youtube.com/watch?v=S7-mXcOhUuk
Git
- How to resolve the git conflicts.
https://www.youtube.com/watch?v=4hImdvGIDCM
Java
-
String Buffer (With code)
-
String Builder (With code) Both of them are coming from which classes
-
Iterator and list of iterator (With code)
-
What is legacy classes in java
-
What is iretryanalizer (How it can be achieved)
What are the steps is used to achieve this
How it can be achieved by the @ annotation -
Is it possible to upcasting using class and class
-
Methods from the string class
-
Cursor in vector class
-
What is upcast and downcast
-
List and set are how different from each other.
-
What are java cursors. And how many types of iterator are present in the cursors
-
Singleton Design pattern
-
Constructor overloading
-
What is this calling statements
-
What are the super calling statement
-
Explain List Interface , Map interface and set interface
-
How to perform the Iteration in these Interface
-
Enumration for used for legacy classes
-
final and finally keyword in the java
-
Can we overload the main method.
-
Idempotent
-
Optional and default method on java 9
-
Can we override and overload the the final methods.
-
How java works internally
-
What is public static void main(String[] args)
-
== and .equals() method
https://youtube.com/watch?v=wydRwIEnaNY intro
- what is recovery testing.
- alpha testing and beta testing.
https://www.youtube.com/watch?v=94ejo4O4jN0 Intro
- Latest locator which are introduced in selenium 4.0
- latest selenium version you are using.
- What is the use of the scenario outline (parametrized scenarios )
Project Based Questions :
-
what type of project you are handled and the modules you came across?
-
What bug tracking tool you used and how you work on that?
-
Why the test cases review is required and who all are involved ?
-
What is the difference between the smoke testing , sanity testing and exploratory testing.
-
What are the agile phases.
-
How you select testcases for regression testing.
-
Write some of the possible test cases on ATM Machine ?
-
Have you got any issue that something working fine in the Firefox but not in chrome? At that time what you will do ?
-
What is the difference between inner join and outer join ?
-
Find first 4 highest salaries in employee table ?
-
If 3 employee has the highest salary ? then how you will fetch their details ?
-
What is the difference between Thread.sleep() & selenium.setSpeed() ?
-
What is assertation and what are the types you used ?
-
Along with xpath what are the different methods you have used to locate the web elements ?
-
How do you handle different window ?
-
What is the return type of getwindow handel() ?
-
How to upload and download a file using selenium webdriver ?
-
Which one will execute first, beforemethod or beforetest and why ?
-
Explain oops concepts and how you have used it in your project ?
-
What are the difference between class and object ?
-
Why string is immutable ?
-
What is the difference between volatile and transient ?
-
Do you have an idea on enumeration ?
-
What is hashmap and hash table? where to use hashmap ?
-
What is abstract class and have you used it in your project ?
-
What is exception handling - can we have multiple catch for same try and how it is written ?
-
if exception occurs in finally block what will happen ?
-
leap year prog.
-
binary search prog.
-
fibo prog.
-
How to run testcases in parallel ?
-
Why do we use maven ?
-
How you work with SVN ?
-
what is the difference between bug and defects ?
-
What is acceptance testing? when we do it ?
-
What are some important testing metrics ?
-
What are cross-browser testing ?
-
Why do you choose testing not development ?
Code
-
//\u000d System.out.println("Hello"); = It will print the hello the above code thinks like new line
-
Find the first non reparative character in the given string.
EY Question :
-
How to generate reports if we don’t have permission to use any external package for the report?
We also can’t use HTML reports generated by TestNG.