type of testing

Search

Total Views

Total Views:

✅ Selenium with Java Automation Interview Q&A – Part 01



✅ 1. What is Selenium?

Answer:
Selenium is an open-source automation testing tool for web applications. It allows testers to write scripts that simulate real user actions such as clicking, typing, and validating data on web browsers. It supports multiple languages, but Java is the most widely used.

Example:
Automating a login process by entering credentials and validating the redirected page.


✅ 2. What are the components of Selenium?

Answer:

  1. Selenium IDE – Record & playback tool (Firefox/Chrome extension).

  2. Selenium RC – Deprecated remote control-based testing.

  3. Selenium WebDriver – Modern and most used tool for browser automation.

  4. Selenium Grid – Runs tests in parallel on multiple environments.

Example:
In a project, Selenium WebDriver is used to automate UI tests, and Selenium Grid is used to execute them on different browsers simultaneously.


✅ 3. What is WebDriver in Selenium?

Answer:
WebDriver is a Selenium component that directly communicates with the browser to perform actions like clicking buttons, typing text, and verifying elements. It provides a programming interface to create test scripts in Java or other languages.

Example:

WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

✅ 4. How do you launch a browser using Selenium WebDriver?

Answer:
To launch Chrome:

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");

Example:
This script opens the Chrome browser and navigates to Google.


✅ 5. What are locators in Selenium?

Answer:
Locators are used to identify elements on a web page. Common locators include:

  • id

  • name

  • className

  • tagName

  • linkText

  • partialLinkText

  • cssSelector

  • xpath

Example:

driver.findElement(By.id("username"));
driver.findElement(By.xpath("//input[@type='submit']"));

✅ 6. Difference between findElement() and findElements()?

Answer:

  • findElement() – Returns a single element. Throws an exception if not found.

  • findElements() – Returns a list of elements. Returns an empty list if nothing is found.

Example:

WebElement loginBtn = driver.findElement(By.id("login"));
List<WebElement> allLinks = driver.findElements(By.tagName("a"));

✅ 7. How do you perform a click action in Selenium?

Answer:
Use click() method on a WebElement.

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

Example:
To click a “Sign In” button, locate the element and use click().


✅ 8. How to type text into an input box?

Answer:
Use sendKeys() method:

driver.findElement(By.id("username")).sendKeys("admin");

Example:
Fills in the username field with “admin”.


✅ 9. How do you handle dropdowns in Selenium?

Answer:
Use the Select class:

Select dropdown = new Select(driver.findElement(By.id("country")));
dropdown.selectByVisibleText("India");

Also supports selectByIndex() and selectByValue().


✅ 10. How to verify text on a web page?

Answer:
Use getText():

String message = driver.findElement(By.id("successMsg")).getText();
Assert.assertEquals(message, "Login successful");

✅ 11. How do you capture a screenshot in Selenium?

Answer:
Use TakesScreenshot interface:

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));

✅ 12. What are waits in Selenium?

Answer:
Waits are used to pause execution until a condition is met. Types:

  • Implicit Wait

  • Explicit Wait

  • Fluent Wait

Used to handle dynamic elements.


✅ 13. What is Implicit Wait?

Answer:
Sets a default wait time for the driver.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Applies to all elements globally.


✅ 14. What is Explicit Wait?

Answer:
Waits for a specific condition.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit")));

✅ 15. What is the difference between Implicit and Explicit Wait?

Answer:

  • Implicit Wait is global.

  • Explicit Wait is for a specific condition.

  • Explicit is more flexible and powerful.


✅ 16. What is XPath in Selenium?

Answer:
XPath is a locator strategy used to find elements using XML path syntax. Can be:

  • Absolute XPath: /html/body/div[2]/form/input

  • Relative XPath: //input[@id='username']


✅ 17. What is the difference between Absolute and Relative XPath?

Answer:

  • Absolute XPath starts from root node. Fragile.

  • Relative XPath starts from anywhere in the DOM. More reliable.

Use relative XPath in real-time projects.


✅ 18. How do you perform mouse actions in Selenium?

Answer:
Use Actions class:

Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();

✅ 19. How do you handle alerts in Selenium?

Answer:
Use Alert interface:

Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.getText();

✅ 20. How to handle multiple browser windows or tabs?

Answer:
Use getWindowHandles():

Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
driver.switchTo().window(handle);
}

✅ 21. What is Page Object Model (POM)?

Answer:
Page Object Model is a design pattern in Selenium used to create an object repository for web elements. It helps keep test code clean by separating test logic from element locators and actions.

Each web page is represented as a Java class, and the elements are defined as variables with actions as methods.

Example:

public class LoginPage {
WebDriver driver;
@FindBy(id = "username")
WebElement username;
@FindBy(id = "password")
WebElement password;
@FindBy(id = "login")
WebElement loginBtn;
public void login(String user, String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginBtn.click();
}
}

✅ 22. What is the difference between get() and navigate().to()?

Answer:

  • driver.get("url") – Opens the URL and waits for the page to load completely.

  • driver.navigate().to("url") – Similar to get, but also allows navigation functions like back/forward.


✅ 23. How do you refresh a web page in Selenium?

Answer:

driver.navigate().refresh();

OR

driver.get(driver.getCurrentUrl());

✅ 24. How to switch to a frame in Selenium?

Answer:
Use switchTo().frame():

driver.switchTo().frame("frameName");
driver.switchTo().frame(0);
driver.switchTo().frame(driver.findElement(By.id("frameId")));

To return to the main page:

driver.switchTo().defaultContent();

✅ 25. How to perform drag and drop in Selenium?

Answer:

Actions action = new Actions(driver);
action.dragAndDrop(sourceElement, targetElement).perform();

✅ 26. What is TestNG?

Answer:
TestNG (Test Next Generation) is a testing framework inspired by JUnit. It supports annotations, parallel execution, test configuration, dependency testing, and data-driven testing.

Example:

@Test
public void loginTest() {
// test logic
}

✅ 27. What are TestNG annotations?

Answer:
Some commonly used TestNG annotations:

  • @BeforeSuite

  • @BeforeClass

  • @BeforeMethod

  • @Test

  • @AfterMethod

  • @AfterClass

  • @AfterSuite

They help define the flow of test execution.


✅ 28. How do you group tests in TestNG?

Answer:
Use groups attribute:

@Test(groups = {"regression"})
public void test1() { }

Groups can be included/excluded in testng.xml.


✅ 29. How do you skip a test case in TestNG?

Answer:
Use enabled = false:

@Test(enabled = false)
public void skippedTest() { }

Or use throw new SkipException("reason"); inside test logic.


✅ 30. What is DataProvider in TestNG?

Answer:
Used for data-driven testing. You can pass multiple sets of data to a test method.

Example:

@DataProvider(name = "loginData")
public Object[][] data() {
return new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} };
}
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
// login logic
}

✅ 31. How to read data from Excel in Selenium?

Answer:
Use Apache POI library:

FileInputStream fis = new FileInputStream("data.xlsx");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheet("Sheet1");
String data = sheet.getRow(0).getCell(0).getStringCellValue();

✅ 32. What is the difference between close() and quit()?

Answer:

  • close() – Closes the current browser window.

  • quit() – Closes all browser windows and ends the WebDriver session.


✅ 33. How do you perform keyboard events in Selenium?

Answer:
Use sendKeys() or Actions class:

element.sendKeys(Keys.ENTER);

Or:

Actions actions = new Actions(driver);
actions.sendKeys(Keys.CONTROL, "a").perform();

✅ 34. How do you run tests in multiple browsers?

Answer:
Use TestNG with @Parameters or create a factory setup to initialize different WebDriver instances like ChromeDriver, FirefoxDriver, EdgeDriver.


✅ 35. What is headless browser testing?

Answer:
Running browser automation without a UI. Faster and useful for CI/CD.

Example:

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);

✅ 36. How do you handle pop-ups or authentication dialogs?

Answer:
Authentication via URL:

driver.get("https://username:password@site.com");

For JavaScript alerts, use Alert interface.


✅ 37. What is fluent wait?

Answer:
A type of wait where you can define the frequency of checks along with the timeout.

Example:

Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);

✅ 38. What is the difference between assert and verify?

Answer:

  • Assert – Stops execution if condition fails.

  • Verify – Logs failure but continues execution.

Selenium by default uses assertions from TestNG or JUnit.


✅ 39. How do you upload a file in Selenium?

Answer:
Use sendKeys() with file path:

driver.findElement(By.id("upload")).sendKeys("C:\\path\\to\\file.txt");

Works only if <input type="file"> is used.


✅ 40. How do you handle dynamic elements?

Answer:
Use strategies like:

  • Dynamic XPath: //div[contains(@id,'user')]

  • Waits: Explicit or Fluent Wait

  • Regex in XPath or using starts-with, contains


✅ 41. What is WebDriverManager?

Answer:
A library that automatically manages browser drivers for Selenium. Eliminates manual driver setup.

Example:

WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();

✅ 42. How do you maximize the browser window?

Answer:

driver.manage().window().maximize();

✅ 43. How do you delete cookies in Selenium?

Answer:

driver.manage().deleteAllCookies();

✅ 44. How to get title and URL of the page?

Answer:

String title = driver.getTitle();
String url = driver.getCurrentUrl();

✅ 45. How to handle stale element exceptions?

Answer:
Re-locate the element before every action, especially after a page reload.

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

✅ 46. What is JavascriptExecutor in Selenium?

Answer:
Used to run JavaScript code on a web page.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");

✅ 47. How do you scroll in Selenium?

Answer:
Use JavascriptExecutor:

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

✅ 48. What are some limitations of Selenium?

Answer:

  • Cannot test desktop/mobile apps.

  • No built-in reporting.

  • Needs third-party tools for test management.

  • Cannot handle CAPTCHA, barcode, or OTP.


✅ 49. How do you generate reports in Selenium?

Answer:
Use TestNG + ExtentReports or Allure Reports.

Example with ExtentReports:

ExtentReports report = new ExtentReports();
ExtentTest test = report.createTest("Login Test");
test.pass("Login successful");

✅ 50. How do you perform parallel testing?

Answer:
Use TestNG parallel attribute in testng.xml or use Selenium Grid to execute tests on multiple machines/browsers simultaneously.


✅ 51. What is the difference between Selenium and QTP/UFT?

Answer:

Feature Selenium QTP/UFT
Cost Open-source Commercial (paid)
Application Web applications only Web, Desktop, and Mobile
Languages Java, C#, Python, etc. VBScript only
Browser Support Chrome, Firefox, Edge, etc. IE, Chrome, Firefox
OS Support Windows, Linux, macOS Windows only

Selenium is more flexible and widely used in Agile environments.


✅ 52. How do you run Selenium tests using Maven?

Answer:

  1. Add Selenium & TestNG dependencies in pom.xml.

  2. Use mvn clean test to execute.

Example pom.xml:

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.16.1</version>
</dependency>

✅ 53. What is a Maven Surefire plugin?

Answer:

It is used to run unit tests during the build phase. TestNG or JUnit tests are triggered using this plugin.

Example:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
</plugin>

✅ 54. How do you capture logs in Selenium?

Answer:

Use Log4j or Java’s built-in logging framework.

Log4j Example:

Logger log = Logger.getLogger("MyLogger");
log.info("Test started");

✅ 55. How do you perform database testing using Selenium?

Answer:

Selenium cannot directly interact with databases, but you can use JDBC (Java Database Connectivity) with Selenium scripts.

Example:

Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

✅ 56. How do you handle SSL certificate errors in Selenium?

Answer:

For Chrome:

ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
WebDriver driver = new ChromeDriver(options);

✅ 57. What is a Hybrid Framework in Selenium?

Answer:

A Hybrid Framework combines multiple frameworks like Data-Driven, Keyword-Driven, and Modular frameworks. It provides flexibility and reusability in test automation.


✅ 58. What is a Keyword-Driven framework?

Answer:

In this framework, keywords (actions) like CLICK, ENTER, SELECT are defined in an external file (e.g., Excel). The script reads and executes these keywords using a keyword engine.


✅ 59. What is a Data-Driven framework?

Answer:

Test data is stored separately in Excel, CSV, or database. The same test script runs multiple times with different sets of data using @DataProvider.


✅ 60. What is Jenkins?

Answer:

Jenkins is a Continuous Integration (CI) tool used to automate test execution. It integrates with version control tools (like Git) and triggers Selenium test runs automatically on code changes.


✅ 61. How do you integrate Jenkins with Selenium?

Answer:

  1. Install Jenkins and required plugins (Maven/TestNG).

  2. Create a Maven job.

  3. Connect to Git repo.

  4. Configure mvn clean test command.

  5. Add post-build actions for reports.


✅ 62. What is Continuous Integration in test automation?

Answer:

CI is the practice of automatically integrating code changes and running automated tests frequently (often after every commit). It ensures bugs are caught early and code quality is maintained.


✅ 63. What is Git and how is it used in automation?

Answer:

Git is a version control system. In automation:

  • You store and version your Selenium test code.

  • Collaborate with team members.

  • Trigger builds from Git commits.

Common commands: git clone, git pull, git push, git commit.


✅ 64. What is GitHub Actions?

Answer:

GitHub Actions is a CI/CD tool built into GitHub. It allows you to automate Selenium test execution workflows based on events like push, pull request, etc.


✅ 65. What is a test suite in TestNG?

Answer:

A TestNG suite is defined in testng.xml, containing one or more test classes to be executed together. It manages test execution order, grouping, and parameters.


✅ 66. What is a soft assertion?

Answer:

Soft assertions (from TestNG or AssertJ) do not stop test execution on failure. All failures are reported at the end.

Example:

SoftAssert soft = new SoftAssert();
soft.assertEquals(actual, expected);
soft.assertAll(); // triggers all collected failures

✅ 67. What is a hard assertion?

Answer:

Hard assertions (like Assert.assertEquals) immediately stop execution if the condition fails.


✅ 68. How do you check if a web element is present on a page?

Answer:

List<WebElement> list = driver.findElements(By.id("elementId"));
if (list.size() > 0) {
System.out.println("Element is present");
}

✅ 69. How do you verify if an element is displayed?

Answer:

if (driver.findElement(By.id("logo")).isDisplayed()) {
System.out.println("Logo is visible");
}

✅ 70. How do you run failed test cases in TestNG?

Answer:

After execution, TestNG creates a testng-failed.xml file. You can rerun it to execute only failed tests.


✅ 71. What is a retry analyzer in TestNG?

Answer:

Retry Analyzer automatically re-executes failed tests.

Example:

@RetryAnalyzer(Retry.class)
@Test
public void test1() { }

✅ 72. What is the purpose of @Factory annotation in TestNG?

Answer:

Used for data-driven parallel execution. It provides different sets of data to a test class constructor.


✅ 73. What is the use of ExpectedConditions in Selenium?

Answer:

It is a utility class that contains predefined conditions for waits like:

  • visibilityOfElementLocated

  • elementToBeClickable

  • alertIsPresent


✅ 74. What is the use of Actions class?

Answer:

Used to perform complex user gestures like:

  • Mouse hover

  • Drag and drop

  • Right-click

  • Double-click


✅ 75. What is Robot class in Java?

Answer:

Used for simulating low-level keyboard and mouse events. Helpful for handling file upload windows, print dialogs, etc.

Example:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);

✅ 76. What is DesiredCapabilities?

Answer:

Used to set browser-specific configurations for Selenium tests like:

  • Accept SSL certificates

  • Set browser name/version

  • Platform type

Now mostly replaced by ChromeOptions, FirefoxOptions.


✅ 77. What is RemoteWebDriver?

Answer:

Used for executing tests remotely using Selenium Grid or cloud platforms (like BrowserStack, Sauce Labs).

WebDriver driver = new RemoteWebDriver(new URL(gridURL), options);

✅ 78. What are some cloud-based tools for Selenium testing?

Answer:

  • BrowserStack

  • Sauce Labs

  • LambdaTest

  • TestingBot

They allow cross-browser testing without local setup.


✅ 79. What is the use of Thread.sleep() in Selenium?

Answer:

It pauses test execution for the specified time (in milliseconds). Not recommended for real projects – better to use Explicit/Fluent waits.


✅ 80. How do you handle timeouts in Selenium?

Answer:

Use timeout management for:

  • Page Load Timeout:

    driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
    
  • Script Timeout:

    driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(20));

✅ 81. What is Selenium Grid?

Answer:

Selenium Grid allows you to run tests on multiple machines and browsers in parallel. It helps in cross-browser and cross-platform testing. You have:

  • Hub: Controls the execution.

  • Nodes: Machines where tests are run.

Example: Run Chrome on Windows and Firefox on Linux at the same time.


✅ 82. What is a TestNG Listener?

Answer:

A listener in TestNG is used to perform actions when test events occur like onTestStart, onTestSuccess, onTestFailure, etc.

Example:

public class MyListener implements ITestListener {
public void onTestFailure(ITestResult result) {
System.out.println("Test Failed: " + result.getName());
}
}

Attach it using @Listeners(MyListener.class) or testng.xml.


✅ 83. What is Page Object Model (POM)?

Answer:

POM is a design pattern where each page of the application has a corresponding Java class. This improves code reusability and readability.

Structure:

  • LoginPage.java: contains WebElements and methods.

  • LoginTest.java: calls those methods.


✅ 84. What is the PageFactory in Selenium?

Answer:

PageFactory is a class in Selenium that supports POM and initializes WebElements using @FindBy.

Example:

@FindBy(id="username") WebElement username;

PageFactory.initElements(driver, this);

✅ 85. What is the difference between @FindBy and driver.findElement()?

Answer:

  • @FindBy: Used with PageFactory; provides lazy initialization.

  • driver.findElement(): Finds the element immediately.

@FindBy is preferred in POM-based frameworks for cleaner code.


✅ 86. What are the different types of waits in Selenium?

Answer:

  1. Implicit Wait: Applies globally for all elements.

  2. Explicit Wait: Waits for a specific condition.

  3. Fluent Wait: Similar to explicit but polls at regular intervals.


✅ 87. How do you perform drag-and-drop in Selenium?

Answer:

Actions action = new Actions(driver);
action.dragAndDrop(source, target).build().perform();

✅ 88. How do you perform mouse hover in Selenium?

Answer:

Actions action = new Actions(driver);
action.moveToElement(menu).perform();

✅ 89. How do you take a screenshot in Selenium?

Answer:

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));

✅ 90. How do you handle pop-ups and alerts in Selenium?

Answer:

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // or alert.dismiss();

✅ 91. How do you handle file uploads in Selenium?

Answer:

If the file input element is of type input[type='file']:

driver.findElement(By.id("upload")).sendKeys("C:\\path\\file.txt");

✅ 92. How do you switch between tabs in Selenium?

Answer:

Set<String> handles = driver.getWindowHandles();
Iterator<String> it = handles.iterator();
String parent = it.next();
String child = it.next();
driver.switchTo().window(child);

✅ 93. How do you handle frames in Selenium?

Answer:

driver.switchTo().frame("frameName"); // or by index or WebElement
driver.switchTo().defaultContent(); // to go back to main page

✅ 94. How do you scroll down a page using JavaScript in Selenium?

Answer:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");

✅ 95. How do you wait for an element to be visible?

Answer:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

✅ 96. How do you validate the title of a page?

Answer:

String title = driver.getTitle();
Assert.assertEquals(title, "Expected Title");

✅ 97. How do you assert the text of an element?

Answer:

String text = driver.findElement(By.id("msg")).getText();
Assert.assertEquals(text, "Login Successful");

✅ 98. What is the use of JavascriptExecutor in Selenium?

Answer:

It is used to run JavaScript code inside the browser. Helpful for clicking hidden elements, scrolling, etc.

Example:

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

✅ 99. How do you generate a dynamic XPath?

Answer:

//tagname[contains(@attribute,'value')]
driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));

✅ 100. What are the common exceptions in Selenium?

Answer:

  • NoSuchElementException

  • StaleElementReferenceException

  • ElementNotInteractableException

  • TimeoutException

  • WebDriverException

Understanding these helps in writing better wait conditions and handling dynamic elements.



Comments

🌟🌟🌟🌟☆ Great platform with helpful onboarding! Some areas could be streamlined, but overall a very positive experience.