type of testing

Search

Total Views

Total Views:

Selenium WebDriver with Java Interview Questions and Answers – Part 02

✅ Selenium WebDriver with Java Interview Questions and Answers – Part 02


✅ 1. What is Selenium WebDriver?

Answer:

Selenium WebDriver is an open-source automation tool used to automate web applications across different browsers like Chrome, Firefox, Edge, and Safari. It interacts directly with the browser and mimics real user actions like clicking, typing, navigating, and validating content.

Selenium WebDriver supports multiple programming languages including Java, Python, C#, and JavaScript.

Example:

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

✅ 2. What are the advantages of Selenium WebDriver?

Answer:

  • Supports multiple browsers (Chrome, Firefox, Edge, Safari)

  • Works on Windows, macOS, and Linux

  • Supports many languages (Java, Python, C#, etc.)

  • Integrates well with frameworks (TestNG, JUnit, Cucumber)

  • Community-supported and open-source

  • Can automate dynamic web elements

  • Supports headless and grid execution


✅ 3. What is the difference between findElement() and findElements()?

Answer:

  • findElement() returns the first matching web element or throws NoSuchElementException if not found.

  • findElements() returns a list of all matching elements. If none found, returns an empty list (no exception).

Example:

WebElement button = driver.findElement(By.id("submit"));
List<WebElement> links = driver.findElements(By.tagName("a"));

✅ 4. What are different types of locators in Selenium?

Answer:

Selenium supports the following locators to identify web elements:

  1. id

  2. name

  3. className

  4. tagName

  5. linkText

  6. partialLinkText

  7. cssSelector

  8. xpath

Example:

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

✅ 5. How do you launch a browser in Selenium?

Answer:

You need to use the WebDriver class specific to the browser.

Example:

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

To use ChromeDriver, make sure you have ChromeDriver.exe in your system path or set the system property.


✅ 6. How do you maximize the browser window?

Answer:

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

This ensures the browser opens in full screen, which is helpful when validating responsive UI elements or locating elements hidden in small screens.


✅ 7. How do you handle dropdowns in Selenium?

Answer:

Use the Select class.

Example:

WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");
select.selectByIndex(2);
select.selectByValue("in");

The dropdown should have <select> tag.


✅ 8. How do you handle alerts in Selenium?

Answer:

Use the Alert interface from Selenium.

Example:

Alert alert = driver.switchTo().alert();
alert.accept(); // Click OK
alert.dismiss(); // Click Cancel
alert.getText(); // Read alert message
alert.sendKeys("input"); // Enter text in prompt

✅ 9. How do you get the text of a web element?

Answer:

String message = driver.findElement(By.id("welcome")).getText();

Use getText() to retrieve visible text from elements like headings, labels, etc.


✅ 10. How do you check if a web element is displayed/enabled/selected?

Answer:

WebElement checkbox = driver.findElement(By.id("agree"));
checkbox.isDisplayed(); // true if visible
checkbox.isEnabled(); // true if interactable
checkbox.isSelected(); // true if checkbox/radio is selected

These methods help in validations.


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

Answer:

Use Actions class.

Example:

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

This is useful for menus that show sub-items on hover.


✅ 12. How do you perform drag and drop?

Answer:

WebElement source = driver.findElement(By.id("drag"));
WebElement target = driver.findElement(By.id("drop"));
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();

This simulates dragging one element and dropping it over another.


✅ 13. How do you scroll a webpage in Selenium?

Answer:

Using JavaScriptExecutor:

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

Or scroll to a specific element:

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

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

Answer:

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

Use Apache Commons IO for FileUtils.


✅ 15. How do you handle multiple browser windows?

Answer:

String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for (String handle : allWindows) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
}
}

You can switch back to main window later:

driver.switchTo().window(mainWindow);

✅ 16. How do you handle frames or iframes?

Answer:
Switch using:

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

Return to main page:

driver.switchTo().defaultContent();

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

Answer:

  • driver.close() – Closes the current tab or window.

  • driver.quit() – Closes all tabs/windows opened by WebDriver and ends the session.

Use quit() at the end of your test execution.


✅ 18. What is Page Object Model (POM) in Selenium?

Answer:

POM is a design pattern where each web page is represented by a separate Java class. It contains web elements and methods to interact with those elements.

Advantages:

  • Code reusability

  • Easy maintenance

  • Clear structure

Example:

public class LoginPage {
WebDriver driver;
@FindBy(id = "username")
WebElement username;
public void enterUsername(String user) {
username.sendKeys(user);
}
}

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

Answer:

Use WebDriverWait and ExpectedConditions:

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

This is better than using Thread.sleep().


✅ 20. What is the difference between implicit and explicit wait?

Answer:

  • Implicit Wait: Waits globally for all elements before throwing exception.

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  • Explicit Wait: Waits for specific condition for a specific element.

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

Use explicit wait for dynamic elements.


✅ 21. What is WebDriverWait in Selenium?

Answer:

WebDriverWait is an explicit wait provided by Selenium to pause the execution until a certain condition is met or timeout occurs. It helps in handling dynamic web elements that may take time to load.

Example:

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

This waits up to 10 seconds for the element with ID loginButton to become visible.


✅ 22. How do you handle dynamic web elements in Selenium?

Answer:

Dynamic elements have IDs or attributes that change each time the page loads. We handle them using:

  • XPath with contains(), starts-with()

  • CSS selectors

  • Waits

Example using XPath:

driver.findElement(By.xpath("//input[contains(@id,'username')]")).sendKeys("admin");

✅ 23. What is the difference between XPath and CSS Selector?

Answer:

XPath CSS Selector
Can traverse both forward and backward in DOM Only forward traversal
Syntax is slightly more complex More readable
Slower performance Faster in most browsers
Supports functions like contains, starts-with Limited functions

Example:

  • XPath: //div[@class='title']

  • CSS: div.title


✅ 24. How do you verify the title of a webpage?

Answer:

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

This is used to verify if the correct page has loaded.


✅ 25. How do you verify if a certain text is present on the page?

Answer:

Use XPath or page source:

boolean isPresent = driver.getPageSource().contains("Welcome User");
Assert.assertTrue(isPresent);

Or:

String message = driver.findElement(By.xpath("//h2")).getText();
Assert.assertEquals(message, "Welcome User");

✅ 26. How do you close pop-ups or modal windows?

Answer:

  • Use driver.switchTo().alert() for JS alerts

  • Use findElement().click() for modal close buttons

  • Use JavaScript if needed

Example:

driver.findElement(By.cssSelector(".modal-close")).click();

✅ 27. What are the types of waits in Selenium?

Answer:

  1. Implicit Wait – waits globally

  2. Explicit Wait – waits for a specific condition

  3. Fluent Wait – custom wait with polling interval


✅ 28. What is FluentWait in Selenium?

Answer:

FluentWait defines maximum wait time, polling interval, and exceptions to ignore.

Example:

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

✅ 29. How do you capture tooltip text in Selenium?

Answer:

WebElement element = driver.findElement(By.id("helpIcon"));
String tooltip = element.getAttribute("title");

Tooltips are often stored in the title attribute.


✅ 30. How do you simulate pressing keyboard keys?

Answer:

Use Actions or sendKeys():

Actions actions = new Actions(driver);
actions.sendKeys(Keys.ENTER).perform();

or:

driver.findElement(By.id("input")).sendKeys(Keys.TAB);

✅ 31. How to handle SSL certificate errors in Selenium?

Answer:

Use DesiredCapabilities or options to accept insecure certificates.

Example for Chrome:

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

✅ 32. How do you switch to a new browser tab in Selenium?

Answer:

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

You can store handles in a List for easier access.


✅ 33. How do you get the attribute value of an element?

Answer:

String value = driver.findElement(By.id("username")).getAttribute("value");

Useful for checking field values, placeholders, etc.


✅ 34. How do you check the background color or CSS value?

Answer:

String color = driver.findElement(By.id("button")).getCssValue("background-color");

Used for visual UI validation.


✅ 35. How do you simulate double-click in Selenium?

Answer:

Actions actions = new Actions(driver);
actions.doubleClick(driver.findElement(By.id("submitBtn"))).perform();

✅ 36. How do you simulate right-click (context click)?

Answer:

Actions actions = new Actions(driver);
actions.contextClick(driver.findElement(By.id("menu"))).perform();

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

Answer:

Use sendKeys() to set file path.

driver.findElement(By.id("fileUpload")).sendKeys("C:\\Users\\file.pdf");

Make sure the <input type='file'> tag is present.


✅ 38. How do you download a file using Selenium?

Answer:

Selenium doesn’t handle downloads directly. You can:

  • Configure browser settings (like ChromeOptions)

  • Use tools like Robot class or AutoIt for dialogs

  • Validate if the file exists in the download directory after test


✅ 39. How do you take a full page screenshot?

Answer:

Use third-party tools like AShot or full-screen extensions.

Basic screenshot:

TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);

For full page:

  • Use AShot (Java library)

  • Use Firefox full-page option


✅ 40. What are DesiredCapabilities in Selenium?

Answer:

DesiredCapabilities was used to set browser-specific settings (e.g., browser name, version, platform), but now it’s deprecated and replaced by Options classes (e.g., ChromeOptions, FirefoxOptions).


✅ 41. What is the use of TestNG in Selenium?

Answer:

TestNG is a testing framework used with Selenium to manage test cases, group them, add dependencies, and generate test reports. It supports:

  • Test prioritization

  • Data-driven testing

  • Parallel execution

  • HTML reporting


✅ 42. How do you write a basic TestNG test?

Answer:

@Test
public void loginTest() {
driver.get("https://app.com");
driver.findElement(By.id("user")).sendKeys("admin");
driver.findElement(By.id("pass")).sendKeys("admin123");
driver.findElement(By.id("login")).click();
}

✅ 43. What are TestNG annotations?

Answer:

TestNG provides annotations like:

  • @BeforeSuite, @BeforeClass, @BeforeMethod

  • @Test

  • @AfterMethod, @AfterClass, @AfterSuite

They define the order of execution.


✅ 44. What is priority in TestNG?

Answer:

@Test(priority = 1)
public void firstTest() { }
@Test(priority = 2)
public void secondTest() { }

Lower priority values are executed first.


✅ 45. How do you use dependsOnMethods in TestNG?

Answer:

@Test
public void login() {}
@Test(dependsOnMethods = "login")
public void createUser() {}

This ensures createUser() runs only if login() passes.


✅ 46. How do you run multiple test classes in TestNG?

Answer:

Create a TestNG XML file:

<suite name="Suite">
<test name="TestClasses">
<classes>
<class name="tests.LoginTest"/>
<class name="tests.HomeTest"/>
</classes>
</test>
</suite>

Run using TestNG runner.


✅ 47. How do you run test cases in parallel?

Answer:

In TestNG XML, add:

<suite name="Suite" parallel="tests" thread-count="2">

This runs tests in parallel using 2 threads.


✅ 48. What is DataProvider in TestNG?

Answer:

@DataProvider is used for data-driven testing. It supplies multiple sets of data to a test method.

Example:

@DataProvider(name = "loginData")
public Object[][] getData() {
return new Object[][] {{"admin", "123"}, {"user", "456"}};
}
@Test(dataProvider = "loginData")
public void loginTest(String user, String pass) {
// use user and pass
}

✅ 49. What is soft assertion in TestNG?

Answer:

SoftAssert doesn’t stop the test if one assertion fails. It collects all failures and reports them at the end.

Example:

SoftAssert sa = new SoftAssert();
sa.assertEquals(actual1, expected1);
sa.assertEquals(actual2, expected2);
sa.assertAll(); // must be called at end

✅ 50. What is the difference between Assert and SoftAssert?

Feature Assert SoftAssert
Stops test on failure Yes No
Final assertAll() needed No Yes
Use Case Critical checks Multiple validations

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

Answer:

You can skip a test in two ways:

1. Using enabled = false:

@Test(enabled = false)
public void skipThisTest() {
// This test will not run
}

2. Programmatically using SkipException:

@Test
public void skipTest() {
throw new SkipException("Skipping this test deliberately");
}

✅ 52. What is the difference between @BeforeMethod and @BeforeClass in TestNG?

Annotation Execution Time Usage
@BeforeMethod Runs before every test method Use it to initialize test preconditions
@BeforeClass Runs once before all test methods Use it to initialize things like browser

Example:

@BeforeClass
public void setUp() {
driver = new ChromeDriver();
}
@BeforeMethod
public void goToHomePage() {
driver.get("https://example.com");
}

✅ 53. How do you create a TestNG test suite?

Answer:

By creating an XML file with <suite> and <test> tags.

Example (testng.xml):

<suite name="AutomationSuite">
<test name="RegressionTests">
<classes>
<class name="tests.LoginTest"/>
<class name="tests.DashboardTest"/>
</classes>
</test>
</suite>

Run using:

Right-click testng.xml → Run as → TestNG Suite

✅ 54. What is the use of @AfterSuite in TestNG?

Answer:

@AfterSuite runs after all test cases in the suite have been executed. It's used for final cleanup, like closing reports or sending email notifications.

@AfterSuite
public void tearDownSuite() {
System.out.println("All tests finished. Generating reports...");
}

✅ 55. How do you handle exceptions in Selenium?

Answer:

Use try-catch blocks to handle exceptions like NoSuchElementException, TimeoutException.

Example:

try {
driver.findElement(By.id("login")).click();
} catch (NoSuchElementException e) {
System.out.println("Login button not found!");
}

✅ 56. What is Page Object Model (POM) in Selenium?

Answer:

Page Object Model is a design pattern where each web page is represented as a Java class. All page elements and actions are stored in that class, making test code clean and reusable.

Benefits:

  • Better code readability

  • Easy maintenance

  • Reduces duplication


✅ 57. How do you implement Page Object Model?

Answer:

Step 1: Create a page class:

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

Step 2: Call from test:

LoginPage lp = new LoginPage(driver);
lp.login("admin", "123");

✅ 58. What is PageFactory in Selenium?

Answer:

PageFactory is a Selenium class used to initialize web elements defined with @FindBy.

PageFactory.initElements(driver, this);

It improves code readability and reduces the need to repeatedly use driver.findElement.


✅ 59. What is the difference between POM and PageFactory?

Feature POM PageFactory
Approach Manual element initialization Uses annotations and lazy loading
Code driver.findElement() @FindBy + PageFactory.initElements()
Performance Slightly slower Faster due to caching and lazy loading

✅ 60. What are test groups in TestNG?

Answer:

Test groups allow you to organize tests by categories like "smoke", "regression", "sanity".

Example:

@Test(groups = {"regression"})
public void testOne() {}
@Test(groups = {"smoke"})
public void testTwo() {}

In your TestNG XML:

<groups>
<run>
<include name="smoke"/>
</run>
</groups>

✅ 61. What is alwaysRun=true in TestNG?

Answer:

If a method depends on another test, but you want it to run regardless of failure, use:

@Test(dependsOnMethods = {"login"}, alwaysRun = true)
public void logoutTest() {}

✅ 62. What is the difference between hard and soft assertion?

Answer:

Hard Assert Soft Assert
Stops test on failure Continues test execution
Provided by Assert Provided by SoftAssert
No need for assertAll() Must use assertAll()

✅ 63. What is the use of ITestListener in TestNG?

Answer:

ITestListener is used to listen to test events such as test start, success, failure, etc. Helps in creating custom logs or screenshots on failure.

Example:

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

✅ 64. How do you integrate listeners in TestNG?

Answer:

Use @Listeners annotation:

@Listeners(CustomListener.class)
public class MyTestClass {
// tests here
}

Or add in testng.xml:

<listeners>
<listener class-name="listeners.CustomListener"/>
</listeners>

✅ 65. How do you run failed test cases only?

Answer:

  1. After first run, TestNG generates testng-failed.xml

  2. Right-click testng-failed.xml → Run as TestNG Suite

Only failed tests will execute again.


✅ 66. How do you capture screenshots on test failure?

Answer:

Use ITestListener and TakesScreenshot:

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

Call this in onTestFailure() of a listener.


✅ 67. How do you run Selenium tests from command line?

Answer:

  • Use Maven or TestNG XML.

  • Command:

mvn test

or

java -cp "bin;libs/*" org.testng.TestNG testng.xml

✅ 68. How do you run Selenium tests in Jenkins?

Answer:

  1. Install Jenkins and configure Java + Maven

  2. Create a Freestyle or Pipeline project

  3. Add GitHub repo or local code

  4. Add build step: mvn test

  5. Save and build


✅ 69. How do you use parameters in TestNG?

Answer:

In XML:

<parameter name="browser" value="chrome"/>

In Java:

@Parameters("browser")
@Test
public void openBrowser(String browserName) {
if (browserName.equals("chrome")) {
driver = new ChromeDriver();
}
}

✅ 70. How do you handle dropdowns in Selenium?

Answer:

Use Select class:

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

You can also use:

  • selectByIndex()

  • selectByValue()


✅ 71. How do you verify if dropdown is multi-select?

Answer:

Select select = new Select(driver.findElement(By.id("options")));
boolean isMulti = select.isMultiple();

✅ 72. How do you select multiple values from a multi-select list?

Answer:

select.selectByIndex(1);
select.selectByIndex(2);

✅ 73. How do you deselect options in a dropdown?

Answer:

select.deselectAll();

or

select.deselectByVisibleText("Option 1");

Only works on multi-select dropdowns.


✅ 74. How do you print all options from a dropdown?

Answer:

List<WebElement> options = select.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
}

✅ 75. How do you get selected value from dropdown?

Answer:

WebElement selected = select.getFirstSelectedOption();
System.out.println(selected.getText());

✅ 76. What are the different locators in Selenium?

Answer:

  1. id

  2. name

  3. className

  4. tagName

  5. linkText

  6. partialLinkText

  7. cssSelector

  8. xpath


✅ 77. What is the most preferred locator?

Answer:

id is most preferred because it is unique and fastest. If not available, use name, cssSelector, or xpath.


✅ 78. How do you verify broken links using Selenium?

Answer:

Use Java HttpURLConnection:

URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
int responseCode = conn.getResponseCode();

If responseCode >= 400, the link is broken.


✅ 79. What are the limitations of Selenium?

Answer:

  • Cannot test desktop or mobile apps directly

  • Cannot handle CAPTCHA

  • Limited reporting

  • Needs programming knowledge

  • No built-in test management or result dashboard


✅ 80. What are the best practices in Selenium automation?

Answer:

  • Use Page Object Model

  • Reuse code with utility functions

  • Add meaningful logs and screenshots

  • Use explicit waits instead of Thread.sleep()

  • Keep locators in one place (object repository)

  • Handle exceptions properly


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

Feature Selenium QTP/UFT
License Open-source Commercial
Scripting Language Java, Python, C#, etc. VBScript
Application Support Web applications only Web, desktop, SAP, mobile, etc.
Browser Support All major browsers Mostly Internet Explorer, limited
OS Support Windows, Linux, macOS Windows only

✅ 82. How do you use assertions in Selenium with TestNG?

Answer:

Assertions verify that actual results match expected results.

Example:

Assert.assertEquals(actualTitle, "Expected Title");
Assert.assertTrue(element.isDisplayed());

If the assertion fails, the test will stop there and be marked as failed.


✅ 83. What are the types of waits in Selenium?

Answer:

  1. Implicit Wait – Global wait for finding elements:

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  1. Explicit Wait – Wait for specific conditions:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
  1. Fluent Wait – Advanced wait with polling and exception handling.


✅ 84. What is the default polling time of WebDriverWait?

Answer:

Default polling interval is 500 milliseconds (0.5 seconds). You can customize it using FluentWait.


✅ 85. How do you handle alerts in Selenium?

Answer:

Selenium provides Alert interface to handle browser popups.

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // Click OK
alert.dismiss(); // Click Cancel
alert.sendKeys("text"); // For prompt box

✅ 86. How do you switch between windows in Selenium?

Answer:

Use getWindowHandles() and switchTo().window().

String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for (String win : allWindows) {
if (!win.equals(mainWindow)) {
driver.switchTo().window(win);
}
}

✅ 87. How do you handle frames in Selenium?

Answer:

You can switch to a frame using:

driver.switchTo().frame("frameName"); // by name or ID
driver.switchTo().frame(0); // by index
driver.switchTo().frame(driver.findElement(By.id("frame1"))); // by WebElement
driver.switchTo().defaultContent(); // switch back

✅ 88. What is a WebElement in Selenium?

Answer:

A WebElement represents an element on a web page like button, textbox, link, etc. You interact with it using methods like:

WebElement element = driver.findElement(By.id("submit"));
element.click();
element.sendKeys("text");
element.getText();

✅ 89. What is the use of Actions class in Selenium?

Answer:

Actions class is used to perform advanced user gestures:

  • Mouse Hover

  • Drag and Drop

  • Right Click

  • Double Click

  • Click and Hold

Example:

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

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

Answer:

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

Or using clickAndHold + moveToElement:

actions.clickAndHold(src).moveToElement(dest).release().build().perform();

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

Answer:

  • driver.get("url") – Loads a new page and waits until fully loaded.

  • driver.navigate().to("url") – Also opens URL but allows chaining with forward, back, refresh.


✅ 92. How do you refresh a page in Selenium?

Answer:

driver.navigate().refresh();

✅ 93. How do you handle cookies in Selenium?

Answer:

driver.manage().getCookies(); // Get all
driver.manage().getCookieNamed("Session"); // Get by name
driver.manage().addCookie(new Cookie("user", "swami")); // Add
driver.manage().deleteCookieNamed("Session"); // Delete

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

Answer:

Use JavaScriptExecutor:

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

Or scroll to an element:

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

✅ 95. How do you upload files in Selenium?

Answer:

Use sendKeys() on file input type:

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

No need to handle OS dialog box.


✅ 96. How do you download files using Selenium?

Answer:

Selenium can’t handle download popups directly. You must set browser preferences:

For Chrome:

ChromeOptions options = new ChromeOptions();
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", "C:\\downloads");
options.setExperimentalOption("prefs", prefs);

✅ 97. How do you read data from Excel in Selenium?

Answer:

Use Apache POI:

FileInputStream fis = new FileInputStream("data.xlsx");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheet("Sheet1");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell.getStringCellValue());

✅ 98. How do you generate reports in TestNG?

Answer:

TestNG automatically creates HTML and XML reports in the test-output folder.

To customize, you can integrate ExtentReports, Allure, etc.


✅ 99. What is a Hybrid Framework in Selenium?

Answer:

Hybrid Framework is a combination of multiple frameworks:

  • Data-Driven (Excel or CSV)

  • Keyword-Driven

  • Modular or POM

  • TestNG integration

It gives flexibility and reusability across projects.


✅ 100. What are the challenges you faced in Selenium automation?

Answer:

Some real challenges include:

  • Handling dynamic elements (changing XPath, IDs)

  • Synchronization issues (waits)

  • Browser compatibility

  • Upload/download handling

  • Handling third-party popups or alerts

  • Reporting integration

  • Test data maintenance

  • Flaky tests in CI/CD pipelines

Tip in interviews: Always give 1–2 real examples from your experience.


Comments

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