Selenium + Java Interview Questions
Comprehensive questions covering WebDriver, Java, TestNG, and automation frameworks
Showing 80 of 80 questions
Q1: What is TestNG?
Answer: TestNG is a testing framework for Java inspired by JUnit and NUnit, designed to cover unit, functional, end-to-end, integration testing with powerful features like annotations, grouping, sequencing, and parameterization.
Q2: Advantages of TestNG over JUnit?
Answer: Annotations, parallel execution, data-driven testing, grouping, test dependencies, flexible test configuration, better reporting, and support for multiple test types.
Q3: What are TestNG annotations?
Answer: @Test, @BeforeMethod, @AfterMethod, @BeforeClass, @AfterClass, @BeforeSuite, @AfterSuite, @DataProvider, @Parameters, @BeforeGroups, @AfterGroups
Q4: Execution order of TestNG annotations?
Answer: @BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite
Q5: What is testng.xml?
Answer: Configuration file to define test suites, classes, methods, parameters, and execution settings like parallel execution, groups, and listeners.
Q6: How to run TestNG tests in parallel?
Answer: Set parallel='tests', 'classes', or 'methods' in testng.xml with thread-count attribute. Example: <suite parallel='methods' thread-count='3'>
Q7: What is @DataProvider in TestNG?
Answer: Annotation to supply test data to test methods. Returns Object[][] or Iterator<Object[]>. Example: @DataProvider public Object[][] getData() { return new Object[][]{{"user1", "pass1"}}; }
Q8: How to pass parameters in TestNG?
Answer: Using @Parameters annotation with testng.xml: <parameter name='browser' value='chrome'/> and @Parameters({"browser"}) in test method.
Q9: What are TestNG groups?
Answer: Way to organize tests into categories. Use groups attribute: @Test(groups = {"smoke", "regression"}). Run specific groups via testng.xml.
Q10: How to exclude/include groups in TestNG?
Answer: In testng.xml: <groups><run><include name='smoke'/><exclude name='regression'/></run></groups>
Q11: What are TestNG listeners?
Answer: Classes that listen to TestNG events. Types: ITestListener, ISuiteListener, IReporter. Used for custom reporting, logging, screenshots on failure.
Q12: How to implement ITestListener?
Answer: Implement ITestListener interface, override methods like onTestStart(), onTestSuccess(), onTestFailure(). Add to testng.xml: <listeners><listener class-name='MyListener'/></listeners>
Q13: What is soft assertion in TestNG?
Answer: Continues execution even after assertion failure. Use SoftAssert class: SoftAssert soft = new SoftAssert(); soft.assertEquals(); soft.assertAll();
Q14: Difference between hard and soft assertions?
Answer: Hard assertions stop execution immediately on failure. Soft assertions collect all failures and report at the end using assertAll().
Q15: How to set priority in TestNG?
Answer: Use priority attribute: @Test(priority = 1). Lower numbers execute first. Default priority is 0.
Q16: What is invocationCount in TestNG?
Answer: Runs the same test method multiple times: @Test(invocationCount = 3) runs test 3 times.
Q17: How to make a test method dependent on another?
Answer: Use dependsOnMethods: @Test(dependsOnMethods = {"loginTest"}). Dependent test runs only if dependency passes.
Q18: What is enabled attribute in TestNG?
Answer: Controls whether test should run: @Test(enabled = false) skips the test method.
Q19: How to set timeout for test methods?
Answer: Use timeOut attribute: @Test(timeOut = 5000) fails test if it takes more than 5 seconds.
Q20: What is expectedExceptions in TestNG?
Answer: Expects specific exception: @Test(expectedExceptions = ArithmeticException.class). Test passes only if expected exception is thrown.
Q21: How to run failed tests again in TestNG?
Answer: TestNG generates testng-failed.xml after execution. Run this file to re-execute only failed tests.
Q22: What is @Factory annotation?
Answer: Creates multiple instances of test class with different data: @Factory public Object[] createInstances() { return new Object[]{new TestClass("data1"), new TestClass("data2")}; }
Q23: How to generate reports in TestNG?
Answer: Default reports in test-output folder. Custom reports using IReporter interface or third-party tools like ExtentReports, Allure.
Q24: What is @BeforeGroups and @AfterGroups?
Answer: Runs before/after specific groups: @BeforeGroups("smoke") runs before all smoke group tests.
Q25: How to pass data from one test to another?
Answer: Use ITestContext to set/get attributes: context.setAttribute("key", value); Object value = context.getAttribute("key");
Q26: What is thread-count in TestNG?
Answer: Specifies number of threads for parallel execution: <suite thread-count='5' parallel='methods'>
Q27: How to preserve order of test execution?
Answer: Use preserve-order='true' in testng.xml: <test preserve-order='true'>
Q28: What is @Test(singleThreaded = true)?
Answer: Ensures all methods in the class run in single thread even in parallel execution mode.
Q29: How to retry failed tests automatically?
Answer: Implement IRetryAnalyzer interface, override retry() method, and use @Test(retryAnalyzer = RetryAnalyzer.class)
Q30: What is description attribute in @Test?
Answer: Provides description for test method: @Test(description = "This test validates login functionality")
Q31: What are assertions in TestNG?
Answer: Statements that verify expected vs actual results. TestNG uses Assert class with methods like assertEquals(), assertTrue(), assertNotNull().
Q32: Difference between verify and assert?
Answer: Assert stops execution on failure, verify continues execution and reports failure at the end (soft assertion concept).
Q33: How to use assertEquals in TestNG?
Answer: Assert.assertEquals(actual, expected, "Error message"); Compares two values for equality.
Q34: What is assertNotEquals?
Answer: Assert.assertNotEquals(actual, expected); Verifies that two values are not equal.
Q35: How to assert null values?
Answer: Assert.assertNull(object) checks if object is null. Assert.assertNotNull(object) checks if object is not null.
Q36: What is assertSame vs assertEquals?
Answer: assertSame() checks object reference equality (==), assertEquals() checks value equality using equals() method.
Q37: How to assert collections in TestNG?
Answer: Use assertEquals() for lists/arrays, or iterate and assert individual elements. For custom comparison, implement equals() method.
Q38: What is fail() method in TestNG?
Answer: Assert.fail("message") explicitly fails the test with custom message. Useful for conditional failures.
Q39: How to assert with custom messages?
Answer: All assert methods accept optional message parameter: Assert.assertTrue(condition, "Custom failure message");
Q40: Difference between assertTrue and assertEquals?
Answer: assertTrue(condition) checks if condition is true. assertEquals(actual, expected) checks equality of actual vs expected value.
Q41: What is Selenium Grid?
Answer: Selenium Grid allows parallel execution of tests across multiple machines, browsers, and OS. Reduces total test execution time.
Q42: Difference between Selenium Grid 3 and 4?
Answer: Grid 3: Separate Hub & Node, minimal UI, limited Docker support. Grid 4: Unified distributed architecture, advanced web UI, native Docker support, full W3C WebDriver support.
Q43: How do you set up Selenium Grid?
Answer: Start hub: java -jar selenium-server-standalone.jar -role hub. Start node(s): java -jar selenium-server-standalone.jar -role node -hub http://localhost:4444/grid/register
Q44: How do you run tests in parallel in Selenium?
Answer: Using TestNG: Set parallel='tests' or parallel='methods' in testng.xml. Using Selenium Grid: Tests run on multiple nodes concurrently. Set thread-count attribute.
Q45: Difference between parallel='tests' and parallel='methods'?
Answer: parallel='tests' runs separate <test> tags in parallel. parallel='methods' runs test methods in the same class in parallel.
Q46: How do you pass capabilities for Selenium Grid execution?
Answer: DesiredCapabilities caps = new DesiredCapabilities(); caps.setBrowserName("chrome"); caps.setPlatform(Platform.WINDOWS); WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), caps);
Q47: How do you avoid session conflicts in parallel execution?
Answer: Use thread-safe WebDriver instances (ThreadLocal). Do not share WebDriver instances across threads. Example: ThreadLocal<WebDriver> driver = new ThreadLocal<>();
Q48: How do you handle test data in parallel execution?
Answer: Keep test data isolated per thread. Use unique data sets per test. Avoid shared global variables.
Q49: How do you integrate Selenium Grid with CI/CD pipelines?
Answer: Start Grid on CI agent or Docker container. Trigger tests via Maven/Gradle. Collect reports after execution. Use Jenkins pipelines to run tests across multiple nodes.
Q50: What are the advantages of using Selenium Grid?
Answer: Parallel execution → faster test cycles, cross-browser testing, cross-platform testing, efficient resource utilization.
Q51: How do you handle JavaScript alerts, confirms, and prompts?
Answer: Alert alert = driver.switchTo().alert(); alert.accept(); // OK, alert.dismiss(); // Cancel, alert.getText(); // Get alert text, alert.sendKeys("input"); // For prompt alerts
Q52: How do you handle browser zoom in Selenium?
Answer: Using Actions class with Keys.CONTROL and Keys.ADD / Keys.SUBTRACT. Or using JavaScriptExecutor: js.executeScript("document.body.style.zoom='80%'");
Q53: How do you handle scrolling in Selenium?
Answer: Using JavaScriptExecutor: js.executeScript("window.scrollBy(0,500)"); // Scroll down, js.executeScript("arguments[0].scrollIntoView(true);", element); // Scroll to element
Q54: How do you handle mouse hover in Selenium?
Answer: Using Actions class: Actions actions = new Actions(driver); actions.moveToElement(element).perform();
Q55: How do you perform drag and drop in Selenium?
Answer: Using Actions class: actions.dragAndDrop(sourceElement, targetElement).perform();
Q56: How do you handle right-click context menu?
Answer: Using Actions class: actions.contextClick(element).perform();
Q57: How do you handle keyboard events in Selenium?
Answer: Using Actions class: actions.sendKeys(Keys.ENTER).perform(); actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Q58: How do you handle file upload in Selenium?
Answer: Direct approach (if input type='file'): driver.findElement(By.id("fileUpload")).sendKeys("C:\file.txt"); Using Robot class for OS-level dialog.
Q59: How do you handle hidden elements?
Answer: Selenium cannot click hidden elements directly. Workarounds: Use JavaScriptExecutor to click: js.executeScript("arguments[0].click();", element); Make element visible via JS if possible.
Q60: How do you handle multiple tabs or windows?
Answer: String parent = driver.getWindowHandle(); Set<String> allWindows = driver.getWindowHandles(); for(String window : allWindows){ if(!window.equals(parent)){ driver.switchTo().window(window); } } driver.switchTo().window(parent);
Q61: How do you skip a test dynamically in TestNG?
Answer: if(condition) { throw new SkipException("Skipping this test because condition is true"); }
Q62: How do you run a single test method using TestNG?
Answer: Specify method in testng.xml: <classes><class name='com.test.LoginTest'><methods><include name='loginTest'/></methods></class></classes> Or run via IDE using right-click → Run.
Q63: How do you handle test dependencies in TestNG?
Answer: Using dependsOnMethods or dependsOnGroups: @Test public void loginTest() {} @Test(dependsOnMethods = {"loginTest"}) public void placeOrderTest() {}
Q64: How do you generate HTML reports in TestNG?
Answer: Default TestNG generates reports in test-output folder (index.html). Advanced reports: Integrate Extent Reports or Allure Reports.
Q65: How do you integrate TestNG with Maven or Jenkins?
Answer: Use Maven Surefire Plugin to execute TestNG tests. In Jenkins: Add Maven build step, specify testng.xml as test suite. Collect reports (target/surefire-reports) for CI/CD dashboards.
Q66: How do you handle multiple assertions in a single test?
Answer: Use SoftAssert to continue execution. Collect all assertion results and call soft.assertAll() at the end.
Q67: What are common exceptions in Selenium and how to handle them?
Answer: NoSuchElementException → Check locator, wait for element. StaleElementReferenceException → Re-locate element. TimeoutException → Increase explicit wait. ElementNotInteractableException → Scroll into view or use JS click.
Q68: How do you debug Selenium scripts?
Answer: Use breakpoints in IDE (Eclipse/IntelliJ). Use System.out.println() or logging frameworks. Capture screenshots at failure points. Use step-by-step execution with Thread.sleep() temporarily.
Q69: How do you capture screenshots in Selenium?
Answer: TakesScreenshot ts = (TakesScreenshot) driver; File src = ts.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("screenshot.png"));
Q70: How do you make Selenium scripts maintainable?
Answer: Use Page Object Model (POM) or Page Factory. Keep locators and test data separate. Use utility/helper methods. Modularize scripts into reusable functions. Use meaningful naming conventions.
Q71: How do you handle browser compatibility issues?
Answer: Test on multiple browsers using Selenium Grid. Use cross-browser compatible locators and waits. Regularly update WebDriver to match browser versions.
Q72: How do you improve Selenium test performance?
Answer: Use headless mode for CI/CD. Avoid unnecessary waits; use explicit wait only. Run tests in parallel using TestNG/Grid. Minimize DOM traversal using optimized locators.
Q73: How do you handle dynamic waits for AJAX-heavy applications?
Answer: Use explicit waits for element visibility or text change. FluentWait with polling intervals. Wait for JavaScript ready state: new WebDriverWait(driver, Duration.ofSeconds(10)).until(webDriver → ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Q74: How do you integrate Selenium tests with CI/CD pipelines?
Answer: Use Maven/Gradle to run tests. Jenkins/GitLab pipelines trigger tests on code changes. Collect test reports and artifacts. Run tests on Selenium Grid or Docker containers for parallel execution.
Q75: How do you manage test data for automation?
Answer: Use external files (Excel, CSV, JSON, properties). Use database queries to fetch live test data. Generate dynamic test data using libraries like Faker. Keep test data isolated for parallel tests.
Q76: Best practices for Selenium automation?
Answer: Use POM/Page Factory for maintainability. Avoid Thread.sleep(), use explicit/fluent waits. Keep test data separate. Run tests in parallel for faster execution. Capture logs & screenshots on failure. Use meaningful locators (avoid absolute XPath). Integrate with CI/CD and reporting tools.
Q77: What is Page Object Model?
Answer: Design pattern that creates object repository for web UI elements, making code more maintainable and reusable by separating test logic from page elements.
Q78: Difference between findElement() and findElements()?
Answer: findElement() returns single WebElement, throws exception if not found. findElements() returns List<WebElement>, returns empty list if not found.
Q79: Types of Waits in Selenium?
Answer: Implicit Wait (global timeout), Explicit Wait (specific condition), Fluent Wait (polling frequency + timeout).
Q80: What is Selenium WebDriver?
Answer: WebDriver is a web automation framework that allows you to execute tests across different browsers and platforms, providing programming interface to create and execute test scripts.