0% found this document useful (0 votes)
21 views20 pages

Web & API Automation Testing Interview Prep_ PART-3

Uploaded by

sohelmukadam023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views20 pages

Web & API Automation Testing Interview Prep_ PART-3

Uploaded by

sohelmukadam023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Web & API Automation Testing Interview Prep: PART-3

What is exception ? why it occurs

1. NoSuchElementException

Occurs when Selenium WebDriver tries to identify an element on the web page using a certain locator but
doesn't find it.

Solution: Use explicit waits (WebDriverWait) to wait for the element to be present or visible on the page before
attempting any operation on it.

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someId")));

2. StaleElementReferenceException

Happens when an element is no longer attached to the DOM.

Solution: Re-find the element or use a retry mechanism that can handle this exception and attempt to locate
the element again.

3. TimeoutException

Thrown by WebDriverWait when an expected condition is not met within the time frame defined.

Solution: Adjust timeout settings or review if the expected conditions are correct. Ensure that the webpage is
loaded completely or necessary conditions like visibility or element presence are met before proceeding.

WebDriverWait wait = new WebDriverWait(driver, 15); // Adjust time as necessary

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id ("delayed Element")));


4. ElementNotInteractableException

Occurs when an element is present on the DOM, but it is not in a state that can be interacted with.

Solution: Ensure the element is visible and enabled before taking action. Utilize explicit waits to handle such
scenarios.

WebElement element = new WebDriverWait(driver, 10)

.until(ExpectedConditions.elementToBeClickable(By.id("myElement")));

element.click();

5. ElementClickInterceptedException

Thrown when another element receives the click instead of the intended target element.

Solution: Scroll the element into view, wait until the overlay element disappears or changes position, or use
JavaScript to perform the click.

JavascriptExecutor js = (JavaScriptExecutor) driver;

js.executeScript("arguments[0].scrollIntoView(true);", element);

js.executeScript("arguments[0].click();", element);

6. AssertionError

Occurs in BDD frameworks when the expected state of the application in tests does not match the actual state.

Solution: Review the expectations set in your BDD scenarios and assert statements. Make sure the logic and
conditions are correctly implemented in your step definitions.

Assert.assertTrue("Element should be visible", element.isDisplayed());

Handling Exceptions in a Structured Way:

It’s wise to have a global exception handling strategy, such as implementing a try-catch block at a strategic
point in your code, logging the details of exceptions, and possibly taking screenshots on failures.
try {

// Selenium code that may throw an exception

} catch (NoSuchElementException e) {

// Handle exception or log

} catch (StaleElementReferenceException e) {

// Retry or handle

} catch (Exception e) {

// General catch block for any other exceptions

takeScreenshot(driver, "error.png"); // For debugging purposes

2.use of text() in xpath ?

use of text() in xpath: The text() function in XPath is used to select the text content of a node. It can be very
useful when you need to find an element by its text content:

WebElement element = driver.findElement(By.xpath("//button[text()='Submit']"))

3. why Webdriver driver = new ChromeDriver() is more preferred .

This statement is using the concept of polymorphism where 'driver' is a reference of WebDriver interface and
'new ChromeDriver()' is an object of ChromeDriver class. This way, the same reference can be used to
instantiate other browser classes too like FirefoxDriver, thus making the code more flexible and browser-
independent. This abstraction also makes it easy to switch between different WebDriver implementations.

4. parent class of all exceptions in Java


5.HTTP status codes
6. HTTP Request Methods and difference

7. Remove duplicate elements from array without HashMap in Java


8: Screenshots for full-page and element

public class ScreenshotExample {

public static void main (String[] args) throws IOException {

// Set up WebDriver

System.setProperty("webdriver.chrome.driver", "path/to/your/chromedriver.exe");

ChromeOptions options = new ChromeOptions();

options.addArguments("--start-maximized"); // Maximize browser window for better screenshot results

WebDriver driver = new ChromeDriver(options)

try {

// Navigate to the webpage

driver.get("https://example.com");

// Create an AShot instance with viewport shooting strategy to capture full page

AShot fullPageAShot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000));

Screenshot fullPageScreenshot = fullPageAShot.takeScreenshot(driver);

// Save full page screenshot

ImageIO.write(fullPageScreenshot.getImage(), "PNG", new File("fullPageScreenshot.png"));

// Capture screenshot of a specific element

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

Screenshot elementScreenshot = new AShot().takeScreenshot(driver, element);

// Save element screenshot

ImageIO.write(elementScreenshot.getImage(), "PNG", new File("elementScreenshot.png"));

} finally {

driver.quit();

}
9.RestAssured Questions like what is use of RequestSpecification and
ResponseSpecification

RequestSpecification
• This is used to build the request, such as setting up headers, cookies, body, parameters, timeouts,
etc., and can be reused across different test scenarios and methods.

ResponseSpecification
• This is used to abstract the validation logic of the response, such as checking status codes, response
time, content type, or even body content. This sustains all assertions collected in one place which can
be reused.
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class APITest {


public static void main(String[] args) {
RestAssured.baseURI = "https://api.example.com";

RequestSpecification requestSpec = new RequestSpecBuilder()


.addHeader("Authorization", "Bearer ACCESS_TOKEN")
.setContentType(ContentType.JSON)
.build();

ResponseSpecification responseSpec = new ResponseSpecBuilder()


.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(5000L)) // Time in milliseconds
.expectBody("status", equalTo("success"))
.build();

given () // Set initial stage of request


. spec(requestSpec) // Pass the predefined request specifications
. body("{ \"query\": \"value\" }")
. when() // Define the method and endpoint
. post("/data")
. then() // Assertions to validate response
. spec(responseSpec) // Pass the predefined response specifications
.log(). all(); // Log all details of the response
} }

10. Different ways to click on an element in Selenium:

• Directly using click() method:

driver.findElement(By.id("buttonID")). click();

• Using Actions class:

new Actions(driver). click(driver.findElement(By.id("buttonID"))). build (). perform ();

• Using JavaScriptExecutor

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.getElementById('buttonID'). click ();");

11.What is JavaScriptExecutor ? write code .

JavaScriptExecutor: It is an interface provided by Selenium WebDriver to perform JavaScript commands.

JavascriptExecutor js = (JavascriptExecutor) driver;

Element elementToClick = driver.findElement(By.id("buttonID"));

js.executeScript("arguments [0]. click ();", elementToClick);


12. Where have you used OOPS Concepts in your framework.

• Base Page Class (Using Inheritance and Abstraction)

public abstract class BasePage {


protected WebDriver driver;

public BasePage(WebDriver driver) {


this.driver = driver;
PageFactory.initElements(driver, this); // Initialize WebElements
}

public abstract boolean isAt(); // Abstract method to be implemented by each page class

protected void clickElement(WebElement element) {


element.click();
}

protected void enterText(WebElement element, String text) {


element.sendKeys(text);
}

protected String getElementText(WebElement element) {


return element.getText();
}
}
1. Inheritance:
a. LoginPage inherits from the abstract BasePage class, gaining access to common Selenium
operations which help us to maintain the DRY principle (Don't Repeat Yourself).
2. Abstraction:
a. BasePage class is abstract, it defines a template for other pages such as LoginPage and
ensures that the shared methods like clickElement, enterText, and getElementText are
not directly instantiated but strategically used by inherited classes. This further hides the
complex interaction with the WebDriver from the final user using higher-level methods.
• Specific Page Class (Using Encapsulation and Polymorphism)

b.LoginPage uses encapsulation to hide the complexity of the UI interactions within its
methods like login, so a user of LoginPage just calls login without worrying about the internal
details like element selectors or waiting logic.
3. Polymorphism:
a. isAt() method in BasePage is abstract, letting us define specific conditions that determine
whether the page is loaded when overriding this method in derived pages, like LoginPage.
• Test Class (Showcasing usage of Inherited Methods)

13. Write Java Code to Print all the Permutations of a given string.
14. Bug Life cycle. Bug Severity,Priority

• New: The defect is logged and status set as New.


• Assigned: The bug is assigned to a developer to be fixed.
• Open: The developer starts analyzing and works on the defect fix.
• Fixed: Developer has fixed the bug & changes status to Fixed.
• Testing: The fix is tested by a tester.
• Closed: If the bug no longer exists, it is marked as Closed.
• Reopened: If the bug still persists, it is reopened and the cycle repeats.

Bug Severity and Priority

• Severity indicates the impact of a bug on the system (Critical, Major, Minor, Trivial).
• Priority indicates the urgency of fixing a bug (High, Medium, Low).

15. Write code for Database Connection.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/myDatabase";
String user = "username";
String password = "password";

try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the database successfully!");
// Perform database operations
} catch (SQLException e) {
e.printStackTrace();
}
}
}

16. How will you do parallel testing using testNg , use of IRetryAnalyzer
Parallel execution in TestNG can be done by setting the parallel attribute in the testng.xml file, and
IRetryAnalyzer is used for re-running failed tests.
TestNG.xml for Parallel Execution:

IRetryAnalyzer Implementation:

17. Write code and explain Singleton design pattern.

Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Pattern Implementation:


18.Examples of Using Singleton in Selenium Java BDD Framework:

1. WebDriver Manager Singleton

A common use of Singleton in Selenium frameworks is to manage the WebDriver instance. This ensures that
the same WebDriver instance is reused across all test scenarios, which can improve the execution speed and
resource efficiency.
2. Configuration Data Singleton

Singleton can also be used to manage configuration settings, which are typically loaded once and read many
times during the test execution.
3. Logging Singleton

In a test framework, it's common to have a centralized logging mechanism that various parts of the code can
use to log messages.
19. Git Commands: fetch, pull, clone

1. Fetch: git fetch origin - Fetch branches and tags from the remote repository to the local repo.
2. Pull: git pull origin master - Fetch from and integrate with another repository or a local branch.
3. Clone: git clone <repo_url> - Clone a repository into a new directory.

20. Find the Kth largest and Kth smallest element in array.
Solution :1

Solution:2
21. Linux commands.

You might also like