Sele


Selenium

Q1. How to handle the overlooped element ?

Ans : Handling overlapped elements in Selenium can be tricky because an element that is covered by another element cannot be interacted with directly.
This often results in an exception like ElementClickInterceptedException or similar errors.

  1. Scroll the Element into View :
    Ensure the element is visible by scrolling to it. Use JavaScript to scroll the element into view.

    public void scrollToElement(WebDriver driver, WebElement element)
    {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].scrollIntoView(true);", element);
    }

  2. Use JavaScript to Click
    If the element is overlapped, a normal click might fail. JavaScript can be used to click the element directly, bypassing the Selenium interaction layer.

    public void clickUsingJS(WebDriver driver, WebElement element) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].click();", element);
    }

  3. Wait Until the Overlay Disappears
    An overlay might be temporary (e.g., a loading spinner). Use Explicit Wait to wait for the overlay to disappear.

    public void waitForOverlayToDisappear(WebDriver driver, By overlayLocator) {
    WebDriverWait wait = new WebDriverWait(driver, 10); // Adjust timeout as needed
    wait.until(ExpectedConditions.invisibilityOfElementLocated(overlayLocator));
    }

  4. Resize the Browser Window
    Resizing the browser window might change the layout and remove the overlap.

    driver.manage().window().setSize(new Dimension(1024, 768)); // Example size

  5. Move the Overlay Using JavaScript

    If the overlay is static and not going away, you can modify its CSS properties to make it non-blocking or hidden.

    public void hideOverlay(WebDriver driver, By overlayLocator) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].style.display='none';", driver.findElement(overlayLocator));
    }
    Q3. How to initiate the driver from webpage ?

Ans : It about the setup Method

  1. First we declear the Webdriver as protected and extend reprt and extent_test as public static.
  2. From properties file we take the retrive two string browsername and runmode
  3. for enabling the run mode we declear the options from there expected browser.
  4. for chromeBrowser we use add argument
    for firefox we use setHeadless(true)
    for EdgeBrowser we use addArgument
  5. Then we maximise the windows from driver.manage().wndow().maximum()
  6. we pass the url from the properties file in driver.get() function
  7. now We pass the path of the extend report to the extend manager.getInstance which we declear in the extend manager class in utils package.
  8. Now we start the test by use the code extent_test = extent_report.startTest(Method method)
    Q4. How to handle excel file ?

Ans : We use Apache poi for accessing the value from the Excel file:
Two dependencies are used a. poi b. poi-ooxml both are offered by the org.apache.poi

  1. First we create one method which which help to load the workbook which will take one parameter that is the filepath.

  2. we pass the filepath to the FileInputStraem and then we pass the reference of that in the workbook. and we keep this in try catch bloack so that if any exception occurs it will handel that.

  3. Now create one function to read the value of the excel this function takes few argument such as the sheetname, rowNo, colNo and and that function will return string value.

  4. In try block we open the sheet by passing the sheet name like
    Sheet sheet = workbook.getSheet(sheetname)
    likewise we will take the row value and check if the row value is not null then try to featch the cell value and if also the cell value in not null then we return one function which will return the string value of the cell.

  5. We will create a function which will take one variable of Cell type and
    and using switch case we try to return the string value.

  6. the condition for the switch case id cell.getCeellType() and case we will check is STRING for string we will return cell.getStringCellValue(), NUMERIC and in numeric we check two thing first is date for that condition will be DateUtil.isCellDataFormatted(cell) and it will return cell.getDateCellValue().toString() and if it is not int then it will return String.valueOf(cell.getNumbericCellValue()) and for boolean it will return the same ie String.valueOf(cell.getBooleanCellValue()) and for blanks it will return empty string and for default it will return the format is not supported.

  7. It will create one more function to close the worbook for that in try it firstly try to find that if workbook in not null then close that .
    Q5. How to handle properties file.

Ans :

  1. First we will create reference variable for File, File InputStream, and Properties.
  2. Initialize the file path , and then load the file using reference of the fileinputStream and use try catch there and in catch give NoFileFoundException
  3. Then create object for the properties and in try catch try to load that prop file.
  4. Create a function that will return string value and take key as parameter and we return prop.getProperty(key);

Q6. How many types of waits are present in the selenium or what is synchronisation ?
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.

Different Expected Conditions For Explicit wait :
a. invisibilityOfElementLocated
b. alertIsPresent
c. frameToBeAvailableAndSwitchToIt
d. elementToBeSelected
e. urlContains
f. urlToBe

Different Exceptions for Fluent wait :
a. StaleElementReferenceException.class
b. ElementNotVisibleException.class
c. ElementNotInteractableException.class
d. TimeoutException.class
e. WebDriverException.class
Q7. what are the some changes takes place in handling dynamic web elements in selenium ?

Ans :

Q8. How we can Handel the Drop Down Event which is in select command.

Ans : * The Select class works only with HTML <select> elements

  1. Select class is used to handle the drop down we can select the values from three way.

Select sc= new Select(element);
i. Select by Value : sc.selectByValue(Value);
ii. Select by VisibleText : sc.selectByPartialText("PartialText")
iii. Select By Index : sc.selectByIndex(3)

If we are not using Select class then we can do that by javaScript executor.

  1. WebElement dd = driver.findElement(By.xath("//loc")); // Use JavascriptExecutor to select the value in the dropdown
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("document.getElementById(dd).value = 'optionValue';");

  • other way to find the elements are :
    a. document.getElementsByClassName('dropdown-class')[0].value = 'optionValue';
    b. document.getElementsByTagName('select')[0].value = 'optionValue';
    c. document.getElementsByName('dropdownName')[0].value = 'optionValue';

  • This method will not trigger any change events associated with a dropdown (i.e., if there are event listeners that rely on user interaction, they may not be triggered).
    If you need to trigger events, you can dispatch a change event using JavaScript:

  1. js.executeScript("arguments[0].value = '" + name + "'; arguments[0].dispatchEvent(new Event('change'));", dd);

  2. Using action class we can do handel DropDown

Actions actions = new Actions(driver);
actions.moveToElement(option).click().perform();
Q9. Action class Use ?

The Action Class in Selenium WebDriver is used to handle a variety of user interactions that require complex sequences of mouse and keyboard events. Below are the main actions you can handle using the Actions class:

  1. Mouse Actions
    a) Clicking
    click(): Performs a single mouse click on a web element.
    doubleClick(): Performs a double-click on a web element.
    contextClick(): Performs a right-click (context click) on a web element.

     Example:
    
     Actions actions = new Actions(driver);
     WebElement element = driver.findElement(By.id("elementId"));
    
     // Single click
     actions.click(element).perform();
    
     // Double click
     actions.doubleClick(element).perform();
    
     // Right-click
     actions.contextClick(element).perform();
    

    b) Mouse Hover
    moveToElement(): Moves the mouse pointer to a specific web element, often used for hovering.

     Example:
    
     Actions actions = new Actions(driver);
     WebElement menu = driver.findElement(By.id("menu"));
     actions.moveToElement(menu).perform();
    

    c) Drag and Drop
    dragAndDrop(): Drag an element from a source to a target.
    dragAndDropBy(): Drag an element by a specified offset.

     Example:
    
     WebElement source = driver.findElement(By.id("source"));
     WebElement target = driver.findElement(By.id("target"));
    
     // Drag and drop
     actions.dragAndDrop(source, target).perform();
    
     // Drag and drop by offset
     actions.dragAndDropBy(source, 100, 50).perform();
    

    d) Click and Hold
    clickAndHold(): Clicks and holds the mouse button on a web element.
    release(): Releases the held mouse button.

     Example:
    
     WebElement element = driver.findElement(By.id("elementId"));
    
     // Click and hold
     actions.clickAndHold(element).perform();
    
     // Release
     actions.release().perform();
    

    e) Scrolling

     moveByOffset(): Moves the mouse pointer by a specified offset.
     scrollToElement() (Selenium 4+): Scrolls to make an element visible.
     scrollByAmount() (Selenium 4+): Scrolls by a specific number of pixels.
    
     Example:
    
     // Scroll to an element
     actions.scrollToElement(element).perform();
    
     // Scroll by offset (e.g., scroll down 500 pixels)
     actions.scrollByAmount(0, 500).perform();
    
  2. Keyboard Actions

    a) Key Press

     sendKeys(): Sends a sequence of keystrokes to the active element or a specific element.
    
     Example:
    
     actions.sendKeys(Keys.ENTER).perform(); // Press Enter key
    

    b) Key Down and Key Up

     keyDown(): Simulates pressing and holding a key.
     keyUp(): Simulates releasing a pressed key.
    
     Example:
    
     actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform(); // Ctrl + A
    
  3. Composite Actions

    You can combine multiple actions into a sequence using the build() and perform() methods.

    Example:

     Actions actions = new Actions(driver);
    
     actions.moveToElement(element).clickAndHold().moveByOffset(50, 0).release().perform();
    
  • Best Practices:

    i. Always use perform() to execute the action.
    ii. Combine actions using build() for complex sequences.
    iii. Ensure proper synchronization (e.g., use waits) before performing actions.
    Q10. How to Handel the disappearing element ?
    Ans :

  1. First we enable the debugger by opening the developer tools and in console we will write
    setTimeout(function() { debugger; }, 5000);
    after 5 sec it will freez and then we write thee xpath
    //div[@class='YGcVZO' and contains(text(),'mobiles')]

  2. We will open the Developer tools and press ctrl+shift+p
    then we enable we search "focus" and enable
    "Emulate a focus Page"
    after creating the xpath we will disable that by doing same.
    Q11. How to take screenshot in selenium ?

Ans : There are two ways to take screenshot in selenium

  1. Using Robot class :
    We can use Robot class to take screenshot. We will follow this process :

  2. Initialize the Robot class
    2. Create a dimension using the toolkit
    3. Create a rectangle
    4. Take image using robot.createScreenCapture()
    5. And then using ImageIO write the the image it takes three parameter first
    one is image name , second name is format third is file name like new File("./ScreeNshot/image.png")

     Code will be like that
    
     Robot robo= new Robot();
     Dimension d= Toolkit.getDefaultToolkit().getScreenSize();
     Rectange rect = new Rectange(d);
     BufferedImage img = robot.createScreenCapture(rect);
     ImageIO.write(img,"PNG",new File("./Screenshot/image.png"))
    
  3. using TakesScreenshot interface :

    We create a function that takes driver as argument and file case name for the image file Name.
    After that

    public static void takeScreenshot(WebDriver driver,String FilecaseName)
    {
    String ScreensotFilename = System.getProperty("User.dir")+"//Screenshots//"+ FilecaseName+".jpg";
    File scr = ((TakeScreenshot) driver.getScreenshotAs(OutputType.FILE));
    try
    {
    FileUtils.copyFile(src, new File(screenshotFilename));
    }
    catch(IOException e)
    {
    e.printStackTrace();
    }
    }
    Q12 : How to take the Screenshot for a particular dimession ?

Ans :

Rectangle rect= new Rectangle(10,10,100,100);
BufferImage img = robot.createScreenCapture(rect)
ImageIO.write(img ,"PNG",new File("./Screenshot/image1.png"))
Q13 : Different ways to click one element using java selenium is

  1. Click() method

    WebElemenet elem = driver.findElement(By.Xpath("Xpath"));
    emem.click();

  2. Using JavaScript Executor

    WebElement elem = driver.findElement(BY.xpath("Xpath"));
    javascripteExecutor js = (JavaScriptExecutor) driver;
    js.executeScript("argument[0].click()",elem);

  3. Using Action class

    WebElement Elem = driver.findElement(BY.xpath("Xpath"));
    Actions actions = new Actions(driver);
    actions.click(elem).perform();
    Q14 : How to handle the different windows or what is getWindowHandle() and getWindowHandles() ?
    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.

WebDriver driver =  new ChromeDriver();
driver.manage().windows().maximum();
driver.get("URL");

String currWindow = driver.getWindowHandle();
WebElement elem = driver.FindElement(By.xpath("path_to_that_element"))
elem.click()

set<String> WindowHandel = driver.getWindowHandles();

for(String handle : WindowHandel){

	if(!handle.equals(currWindow){
		driver.switchTo().window(handle);
		break;
	})
}

driver.close();
driver.switchTo().window(Handle);
driver.quit();

Q15 : What is WebDriver?
Ans :

WebDriver is a fundamental interface provided by Selenium WebDriver,
an automation framework used for testing web applications.
It allows you to programmatically interact with web browsers to
simulate user actions such as clicking, typing, navigating, and interacting with elements on a webpage.

Types of WebDriver :
a. ChromeDriver
b. FirefoxDriver
c. EdgeDriver
d. SafariDriver
e. InternetExplorerDriver
Q16 : How to handel the extend manager.

Ans :
To handel the extend manager we add the dependencies of the extendReports to the pom.xml file. To manage this we create one extend manager to the utilities folder.

public class ExtendManager
{
public static ExtendReports extent;

public static ExtendReports getInstance(String FileCaseName)
{
	if (extend == null)
	{
		extent = new ExtentReport(FileCaseName, true, DisplayOrder.NEWEST_FIRST)
				extend.load(System.getProperty("user.dr")+"//Resources//reportConfig.xml")

extent.addSystemInfo("Selenium Version", "3.141.59").addSystemInfo("Environment", "QA");
}
return extent;

}

}
Q17. How to handle the broken Links.

Ans :

To handle the broken links we have to establish one https connection and check the response code for that if response code is 200 then that link is not broken else link is not working.

public class BrokenLinkManager
{
public static void main(String[] args)
{
// Get all links on the page
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Checking broken links...");
for (WebElement link : links)
{
String url = link.getAttribute("href");
// If the link has a URL
if (url != null && !url.isEmpty())
{
checkLinkStatus(url);
}
}

}


public static void checkLinkStatus(String urlString) 
	{
			try {
    				// Create a URL object
    				URL url = new URL(urlString);

    				// Open a connection to the URL
    				HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    				// Set a timeout to avoid hanging the request
    				httpURLConnection.setConnectTimeout(2000);
    				httpURLConnection.setReadTimeout(2000);

    				// Send the request and get the response code
    				int responseCode = httpURLConnection.getResponseCode();

    				// If the response code is not 200, the link is broken
    				if (responseCode != 200) 
				{
        					System.out.println("Broken link: " + urlString + " (Response Code: " + responseCode + ")");
    					} 
			else 
				{
        					System.out.println("Valid link: " + urlString);
    					}
			} catch (Exception e) {
    				System.out.println("Error checking link: " + urlString + " (" + e.getMessage() + ")");
					      }
		}

}
Q18. Why relative xpath is mostly used?
Ans : a. Relative XPath starts from a specific element or node rather than from the root (html), which makes it more flexible and adaptable to changes in the web page structure.
b. If elements are added or removed from the page, relative XPath often remains functional, as long as the targeted element remains in place.
c. It’s easier to write and maintain because it doesn't depend on the entire document structure (as absolute XPath does).

Q18. What is xpath ?
Ans : A query language which is used to find a node or set of nodes in XML/HTML documents.

Q19. 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.

Q20. 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
Q20. 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.

Q21. 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.
Q22. 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

Q23. 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.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(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();

Q24. 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();

Q25. What are the mrthods present in the Navigation Commands.
Ans :

  1. to() Command
    dr.navigate.to(url);

  2. back() command
    dr.navigate.back();

    1. forward() command
      dr.navigate.forward();

    2. refresh() command
      dr.navigate.refresh();
      Q26. 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();

Q27. 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.
Q28. 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.
Q29. 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.
Some of the major functions of website cookies:

	a. Tracking the browsing activity of the user.
	b. Remembering the login details of the user.
	c. 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”)

Q30 . 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");

Example :
// Switch to the alert
Alert alert = driver.switchTo().alert();

// Get the text of the alert
String alertText = alert.getText();
System.out.println("Alert text: " + alertText);

// Accept the alert (clicks OK)
alert.accept();

Q31. What are the different types of popup ?
Ans: Browser popup : It includes os- level dialogs (e.g., FIle uploads, authentications)
For the we use Robot Class.

Q32. 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();

    1. Using Robot Class :
      a. Using keyboards keys
      Robot robot = new Robot();
      robot.keyPress(KeyEvent.VK_DOWN);
      robot.keyRelease(KeyEvent.VK_DOWN);
      Q33. How to handles different frame?
      Ans :
      Frame are the different html DOM inside a particular dom.
      We can manage switch by three ways:

a. By index
dr.switchTo().frame(0);

b. By ID or Name
dr.switchTo().frame("frameId");
dr.switchTo().frame("frameName");

c. By Element
WebElement frameEl = driver.findElement(By.xpath("Xpath"));
dr.switchTo().frame(frameEl);

  • To return back to parent Dom
    (Suppose you are in nested frame and you want to return back to the parent frame)
    dr.switchTo.parantFrame();
  • To return back to original DOM
    dr.switchTo().defaultFrame();
    Q34. 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 earliest that testcases will be executed.
    If we give the same priority then it will run accordingly to the alphabets.

Q35. 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.

Q36. 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.

Q37. How to handle the parallel Execution.
Ans : Parallel Execution Using TestNG XML Configuration :
The most common approach is to configure parallel test execution using the TestNG XML file.
We can specify parallelism at the level of classes, methods, or tests.

a. Running Tests in Parallel at the Method Level :

	<?xml version="1.0" encoding="UTF-8"?>
	<suite name="TestSuite" parallel="methods" thread-count="3">
			<test name="Test1">
				<classes>
    					<class name="com.test.TestClass" />
				</classes>
			</test>
	</suite>


b. Running Tests in Parallel at the Class Level :

	<?xml version="1.0" encoding="UTF-8"?>
	<suite name="TestSuite" parallel="classes" thread-count="2">
			<test name="Test1">
				<classes>
    					<class name="com.test.TestClass1" />
    					<class name="com.test.TestClass2" />
				</classes>
			</test>
	</suite>
  • In this case, 3 threads will be used. This means that TestNG will execute up to 3 test methods simultaneously.
  • Once one of the threads finishes a test method, another method can be executed in the available thread until all the methods have been executed.
  • Parallel Execution of Methods: With parallel="methods", TestNG will attempt to execute multiple test methods at the same time.
  • The thread-count="3" indicates that 3 threads will be used for this execution.

-> For example, if you have 5 test methods in the suite and thread-count="3", TestNG will run 3 methods at once, and once one finishes, another will be started until all 5 methods are completed.
Scenario Based

Q1. 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

Q2. 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.

Q3. 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.

Q4. 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.

Q5. How to Upload any files?
Ans :
Using the Robot class we can upload any files.
for that we can use the above code

Robot robo = new Robot();
String filePath = FilePath or System.getProperty("user.dir")+"Resources//Upload.txt";

// The StringSelection class is used to copy the file path to the system clipboard.
StringSelector fileSelect = new StringSelector(filePath);
Toolkit.getDefaultToolkit().getsystemClipboard().setContents(fileSelect,null);

robo.keyPress(KeyEvent.VK_CONTROL);
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_CONTROL);
robo.keyRelease(KeyEvent.VK_V);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);