Login / Register |
1 year Java Selenium experience - Quality Analyst in cognizant
#java #selenium #cognizant
Posted by TechElliptica at 08 May 2025 ( Day(s) Before)

What is the difference in findElement and findElements in Selenium ?

In Selenium findElement and findElements are methods used to locate elements on a web page.

findElement method provide first matching element found,
findElements provide List of WebElement for all matching Element.


If Element is not present in Webpage, then findElement throw NoSuchElementException, rather findElements return Empty List of WebElement

Difference between close and quit in Selenium?

whenever we use close method it's simply closes the current handle tab suppose if in a session, we have multiple tabs open then close method will close only the current active tab rather than if we are going to use quit method it will close the entire session so it will close all the tabs inside that session


close() - Only close current active tab
quit() - will close all open tabs (with in a session)

How do you write Dynamic XPath ?

Dynamic XPath is used to locate web elements whose attributes or text values change frequently or depend on runtime data. Instead of using static locators, we write XPath expressions using functions like contains(), starts-with(), or text() to handle partial matches and dynamic content.

We can also construct XPath at runtime in code by inserting dynamic values, such as //td[text()={dataToReplace}], where dataToReplace is a variable.

Using XPath access relationships like following-sibling, preceding-sibling, ancestor, descendant, parent (total 13) allows targeting elements based on their relative position.

In Selenium, a utility method can be created to build dynamic XPaths by replacing placeholders with actual values, making the framework more flexible and maintainable when dealing with changing UI structures.

Can you explain the concept of "Waits" in Selenium?

In Selenium, Waits are used to handle dynamic web elements that may not be immediately available or visible when a script runs. They help in synchronizing the execution of the test script with the state of the web page to avoid ElementNotVisibleException, NoSuchElementException, and similar issues.



Types of Waits in Selenium


1. Implicit Wait


  1. Applies globally to the WebDriver instance.
  2. Tells the WebDriver to poll the DOM for a certain amount of time when trying to find an element if it's not immediately available.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Good for general delays, but less flexible for specific elements or conditions.



2. Explicit Wait


  1. Used for specific elements or conditions.
  2. Waits until a particular condition is true before proceeding.
WebDriverWaitwait=newWebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

More precise and customizable than implicit waits.

Recommended over implicit waits in most scenarios.



3. Fluent Wait (Advanced form of Explicit Wait)


  1. Allows the polling frequency to be specified along with ignoring specific exceptions (e.g., NoSuchElementException).
Wait<WebDriver> fluentWait = newFluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);

fluentWait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));


Best when working with highly dynamic web pages or slow elements.




What all common challenges you faced in your Java Selenium UI Automation?

Despite having a robust test automation framework, we occasionally face specific issues, especially during CI executions. Below are the main challenges and how we address them:



1. Test Flakiness During CI Execution (Jenkins - Headless Mode)


In our CI pipeline (executed via Jenkins), we primarily run tests in headless mode, which sometimes results in flaky test behavior—tests fail in CI but pass locally. To mitigate this:

  1. We have implemented a retry mechanism using the IRetryAnalyzer interface in TestNG to automatically re-run failed tests.
  2. We periodically review and optimize our explicit waits to ensure elements are properly synchronized and UI timing issues are minimized.



2. Handling Environment-Specific Data and Test Failures


To ensure reliability across different environments (QA, UAT, etc.) and avoid failures due to hardcoded data:

  1. All environment-specific configurations (e.g., URLs, credentials, DB connections) are externalized in property files such as qa.properties, uat.properties, etc.
  2. These properties are loaded dynamically based on the runtime environment parameter passed via -Denv=qa.
  3. Instead of relying on static test data, we:
  4. Generate dynamic data at runtime (e.g., unique email IDs, phone numbers) using utility classes.
  5. Leverage backend APIs or direct DB queries to set up required test data when needed.
  6. A centralized ConfigReader class handles configuration loading, while TestDataUtil manages dynamic data generation.
  7. We use a TestContext class to store and retrieve data across test methods, improving test consistency and modularity.

This approach makes our test suite environment-agnostic, reliable, and highly CI/CD compatible.



3. Parallel Execution Challenges (Data Conflicts and Session Collisions)


Running tests in parallel can cause issues when:

  1. Tests share the same test data, sessions, or resources.
  2. There’s a lack of test isolation, leading to interference or race conditions.

To address this:

  1. All tests are designed to be independent and stateless, ensuring they don’t depend on or interfere with one another.
  2. We use ThreadLocal<WebDriver> to ensure thread-safe browser sessions, which is crucial for stable parallel execution.
  3. Test data is generated uniquely per thread at runtime to avoid collisions and maintain test integrity.

This ensures our suite scales reliably even during high-concurrency executions.


Does Java support multiple inheritance?

Java does not support multiple inheritance through classes. This means a class cannot directly inherit from multiple parent classes. This is to avoid complexity and ambiguity issues that can arise from multiple inheritance, such as the "diamond problem".


What are instance variables?

Instance variables are variables declared inside a class but outside any method, constructor, or block.

Instance variables always comes with objects (instance)

They are also known as non-static variables. Each object created from a class gets its own separate copy of the instance variables, which means they hold unique values for each instance. These variables represent the state or attributes of an object.


public class Employee {
// Instance variables
String name;
int age;
}
Employee emp1 = new Employee();
Employee emp2 = new Employee();

emp1.name = "Alice";
emp2.name = "Bob";

System.out.println(emp1.name); // Output: Alice
System.out.println(emp2.name); // Output: Bob

Is Java a pure object-oriented language?

No, Java is not a pure object-oriented language. It supports primitive data types (like int, float, char) that are not objects, which is a departure from the core principle of pure object-oriented languages where everything is an object.

Can a main() method be overloaded?

Yes. But JVM only calls the one with signature: public static void main(String[] args).


For Example:

class MainOverload {
public static void main(String[] args) {
System.out.println("Main method with String[] args");
main("Hello");
main(10);
}
public static void main(String arg) {
System.out.println("Main method with String arg: " + arg);
}

public static void main(int arg) {
System.out.println("Main method with int arg: " + arg);
}
}

How to define a constant variable in Java?

To define a constant variable in Java, you use the keywords final (to make it unchangeable) and usually static (so it belongs to the class, not an instance).


Example:

public class Constants {
public static final double PI = 3.14159;
public static final int MAX_USERS = 100;
}

What is the access scope of a protected method?

Access Scope of a protected Method:

Within the same class: A protected method can be accessed by any code in the same class.
Within subclasses (including different packages): A protected method can be accessed by subclasses (even if they are in different packages).
Within the same package: A protected method can be accessed by any class in the same package, even if it's not a subclass.


Example:

package mypackage;
public class Parent {
protected void showMessage() {
System.out.println("Message from Parent");
}
}

class Child extends Parent {
public void display() {
showMessage(); // Accessing the protected method in subclass
}
}
class SamePackageClass {
public void accessParentMethod() {
Parent p = new Parent();
p.showMessage(); // Accessing the protected method in the same package
}
}


When will you define a method as static?

You would define a method as static in Java when you want the method to belong to the class itself, rather than to an instance of the class. In other words, a static method can be called without creating an object of the class.

Tell me difference between final, finalize and finally ?

final makes variable and method unchangeable. If final applied with variable, it become constant, If final applied with method, we cannot override it and if final applied with class, we cannot inherit that class.


finally ensures execution of code after try-catch. if exception occurs or not, finally block will always execute.


finalize called before object is garbage collected.

Can an abstract class be declared final?

No, an abstract class cannot be declared final in Java.


The keywords abstract and final have opposite meanings:

abstract means: This class is incomplete and meant to be extended by subclasses.

final means: This class is complete and cannot be extended.

Can an interface be final?

No. Interfaces must be implemented, so can't be final.

Sort and array and then find alternate index array?


Example:

input = [1,4,2,5,8,3,2]
Step 1 - Sort array = [1,2,2,3,4,5,8]
Output - [1,2,4,8] - every alternate index (9) and then print that array



public class TechEllipticaAlternateArray {
public static void main(String[] args) {
int[] input = {1, 4, 2, 5, 8, 3, 2};

Arrays.sort(input);
int[] result = new int[(input.length + 1) / 2];
int j = 0;
for (int i = 0; i < input.length; i += 2) {
result[j++] = input[i];
}
System.out.print("Alternate index array: "+Arrays.toString(result));
}
}