Showing posts with label Automation. Show all posts
Showing posts with label Automation. Show all posts

Monday, 28 August 2023

TestNG Questions

Question: TestNG Annotations Answer:
@Test
@BeforeMethod
@AfterMethod
@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@Test(enabled = false)
@Test(enabled = true)
@Test(priority=2)
@Test(priority=5,dependsOnMethods={"method1","method2"})
@Test(dependsOnMethods = {"method1"}, alwaysRun=true)
@Test(groups = { "Group1", "Group2" })
@Parameters({"testparameter1", "testparameter2"})
@Listeners(packagename.ListenerClassName.class)
@Test(dataProvider = "getUserIDandPassword")
@Test(description = "Open Facebook Login Page", timeOut=35000)
@Test(invocationCount = 3, invocationTimeOut = 20000)
@Test(invocationCount = 3, skipFailedInvocations = true)
@Test(invocationCount = 3)
@Test(invocationCount = 7, threadPoolSize = 2) 
Question: Order of TestNG annotations Answer: Order of TestNG annotations is as below:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
Question: Assertion in TestNG Answer: Assertions are used to verify the expected outcomes of test cases. Assertions are essential for test automation as they help validate that the actual results match the expected results during test execution. When an assertion fails, it indicates a test failure, and the testing framework will mark the test as failed.

Here are some commonly used assertion methods in TestNG:
  • assertEquals(expected, actual): Compares the expected value with the actual value and asserts that they are equal.
  • assertNotEquals(expected, actual): Compares the expected value with the actual value and asserts that they are not equal.
  • assertTrue(condition): Asserts that the given condition is true.
  • assertFalse(condition): Asserts that the given condition is false.
  • assertNull(object): Asserts that the given object reference is null.
  • assertNotNull(object): Asserts that the given object reference is not null.
Question: How do you group test methods in TestNG, and what is the purpose of grouping tests? Answer: In TestNG (Test Next Generation), you can group test methods using the groups attribute. Grouping tests allows you to categorize your test methods and execute them selectively. This feature is particularly useful when you want to run specific sets of tests based on different criteria or requirements. For example, you may have a suite of tests that cover basic functionality and another set that focuses on more complex scenarios or integration tests.

import org.testng.annotations.Test;

public class MyTestSuite {
    @Test(groups = "smoke")
    public void testMethod1() {
        // Test logic here
    }

    @Test(groups = "regression")
    public void testMethod2() {
        // Test logic here
    }

    @Test(groups = {"smoke", "regression"})
    public void testMethod3() {
        // Test logic here
    }

    @Test(groups = "integration")
    public void testMethod4() {
        // Test logic here
    }
}
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite">
    <test name="SmokeTests">
        <groups>
            <run>
                <include name="smoke" />
            </run>
        </groups>
        <classes>
            <class name="com.example.MyTestSuite" />
        </classes>
    </test>

    <test name="RegressionTests">
        <groups>
            <run>
                <include name="regression" />
            </run>
        </groups>
        <classes>
            <class name="com.example.MyTestSuite" />
        </classes>
    </test>
</suite>

Question: What is the purpose of the @DataProvider annotation in TestNG? How do you implement data-driven testing using TestNG? Answer: The purpose of the @DataProvider annotation in TestNG is to facilitate data-driven testing, where you can run the same test method with multiple sets of data. Data-driven testing allows you to test various scenarios and edge cases with different input data, making your test suite more robust and comprehensive.

Steps to implement data-driven testing:
  1. Create a Data Provider Method
  2. Annotate the Data Provider Method
  3. Pass Data to Test Method
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExample {

    @DataProvider(name = "testData")
    public Object[][] testData() {
        return new Object[][] {
            { 2, 3, 5 },     // Test Case 1: 2 + 3 = 5
            { -1, 5, 4 },    // Test Case 2: -1 + 5 = 4
            { 0, 0, 0 }      // Test Case 3: 0 + 0 = 0
        };
    }

    @Test(dataProvider = "testData")
    public void testAddition(int num1, int num2, int expectedSum) {
        int actualSum = add(num1, num2);
        assert actualSum == expectedSum : "Addition failed!";
    }

    public int add(int a, int b) {
        return a + b;
    }
}
Question: Explain the concept of dependencies in TestNG. How do you manage test method dependencies using annotations? Answer: In TestNG, dependencies allow you to define a relationship between test methods, specifying that one test method depends on the successful execution of another.

1. dependsOnMethods Attribute
@Test
public void testLogin() {
    // Test login functionality
}

@Test(dependsOnMethods = "testLogin")
public void testDashboard() {
    // Test dashboard functionality that requires successful login
}
2. dependsOnGroups Attribute
@Test(groups = "login")
public void testLogin() {
    // Test login functionality
}

@Test(dependsOnGroups = "login")
public void testDashboard() {
    // Test dashboard functionality that requires successful login
}
Question: How do you perform parallel test execution in TestNG? What are the benefits and challenges of parallel testing? Answer: In TestNG, you can perform parallel test execution by leveraging its built-in support for parallel test execution. Parallel testing allows you to run multiple test methods or test classes concurrently on multiple threads, which can significantly reduce test execution time and improve overall test suite efficiency.

TestNG offers the following options for parallel test execution:

1. Parallel Test Execution at Test Level:

You can specify parallel test execution at the test level using parallel="tests". This allows multiple tags to execute concurrently.
<suite name="MyTestSuite" parallel="tests">
    <test name="Test1">
        <!-- Test configuration and classes go here -->
    </test>
    <test name="Test2">
        <!-- Test configuration and classes go here -->
    </test>
</suite>
2. Parallel Test Execution at Class Level:

You can specify parallel test execution at the class level using parallel="classes". This allows test classes to execute concurrently.
<suite name="MyTestSuite" parallel="classes">
    <test name="MyTestClass">
        <classes>
            <class name="com.example.tests.Class1" />
            <class name="com.example.tests.Class2" />
        </classes>
    </test>
</suite>
3. Parallel Test Execution at Method Level:

You can specify parallel test execution at the method level using parallel="methods". This allows individual test methods to execute concurrently.
<suite name="MyTestSuite" parallel="methods">
    <test name="MyTestClass">
        <classes>
            <class name="com.example.tests.Class1" />
            <class name="com.example.tests.Class2" />
        </classes>
    </test>
</suite>
Parallel Testing Suite with Thread Count:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Parallel Testing Suite">
    <test name="Parallel Tests" parallel="methods" thread-count="2">
        <classes>
            <class name="ParallelTest" />
        </classes>
    </test>
</suite>
Threads in parallel testing refer to different execution paths in which test execution can be divided and run concurrently. For example, if there are two threads and two methods, each thread can execute one method when methods are configured to run in parallel. If there are three methods and two threads, one method will have to wait until a thread becomes available for execution.

In TestNG, we also get the liberty to run a single test method in parallel by configuring it inside the test code itself.
public class TestNG {

    @Test(threadPoolSize = 4, invocationCount = 4, timeOut = 1000)
    public void testMethod() {
        System.out.println("Thread ID Is : " + Thread.currentThread().getId());
    }
}
Parameters in the @Test annotation:
  • threadPoolSize: The number of threads to create for running the test method in parallel.
  • invocationCount: The number of times to invoke the test method.
  • timeOut: The maximum time a test execution should take. If this limit is exceeded, the test fails automatically.

Question: TestNG Groups - Include, Exclude Answer: Include Groups:
The element is used to include specific groups for execution.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite">
    <test name="IncludeGroupsTest">
        <groups>
            <run>
                <include name="smoke" />
                <include name="sanity" />
            </run>
        </groups>
        <classes>
            <class name="com.example.tests.TestClass1" />
            <class name="com.example.tests.TestClass2" />
        </classes>
    </test>
</suite>
Exclude Groups:
The element is used to exclude specific groups from execution.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite">
    <test name="ExcludeGroupsTest">
        <groups>
            <run>
                <exclude name="regression" />
            </run>
        </groups>
        <classes>
            <class name="com.example.tests.TestClass1" />
            <class name="com.example.tests.TestClass2" />
        </classes>
    </test>
</suite>
Question: What are TestNG listeners, and how do you use them to customize test execution behavior or generate custom reports? Answer: TestNG listeners are a powerful feature that allows you to customize the behavior of TestNG during test execution. Listeners are Java classes that implement various TestNG listener interfaces and are registered with the TestNG test suite. These listeners "listen" to events that occur during the test execution lifecycle and can perform actions or provide additional information based on those events.

TestNG provides several listener interfaces that can be used to customize test execution behavior or generate custom reports. Some commonly used TestNG listener interfaces are:
  • ITestListener: Provides methods to handle test-level events such as test start, test success, test failure, and test skipped.
  • ISuiteListener: Provides methods to handle suite-level events such as suite start and suite finish.
  • IInvokedMethodListener: Provides methods such as beforeInvocation() and afterInvocation() to handle events surrounding individual method invocations.
  • IReporter: Allows you to generate custom reports based on test results.
  • IAnnotationTransformer: Allows you to modify test annotations at runtime, such as dynamically changing annotation attributes.
Example of ITestListener:
import org.testng.ITestListener;
import org.testng.ITestResult;

public class CustomTestListener implements ITestListener {

    @Override
    public void onTestStart(ITestResult result) {
        System.out.println("Test Started: " + result.getName());
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        System.out.println("Test Passed: " + result.getName());
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println("Test Failed: " + result.getName());
    }

    @Override
    public void onTestSkipped(ITestResult result) {
        System.out.println("Test Skipped: " + result.getName());
    }

    // Other methods from the ITestListener interface
}
Registering the listener in testng.xml:
<suite name="MyTestSuite">
    <listeners>
        <listener class-name="com.example.listeners.CustomTestListener" />
    </listeners>
    <!-- Test configurations and test classes go here -->
</suite>
Question: Handle test timeouts and set maximum time limits for test methods in TestNG Answer: In TestNG, you can handle test timeouts and set maximum time limits for test methods to prevent tests from running indefinitely and to mark them as failed if they exceed the specified time limit. This is useful for avoiding potential test hang-ups and ensuring that test execution remains efficient.

@Test(timeOut = 3000) // The test method should complete within 3 seconds (3000 milliseconds)
public void testWithTimeout2() throws InterruptedException {
    // Test logic that may take some time to execute
    Thread.sleep(5000); // This test will fail because it exceeds the time limit
}
Question: What are the different types of listeners available in TestNG, and how can you use them to handle test events? Answer: TestNG provides several listener interfaces that allow you to respond to different events during test execution:
  • ITestListener: Provides methods to handle test-level events such as test start, test success, test failure, and test skipped. It allows you to perform actions before and after test execution and respond to test outcomes.
  • ISuiteListener: Provides methods to handle suite-level events such as suite start and suite finish. It allows you to perform actions at the beginning and end of test suite execution.
  • IInvokedMethodListener: Provides methods to handle events surrounding individual method invocations through methods such as beforeInvocation() and afterInvocation().
  • IConfigurationListener: Provides methods to handle configuration method execution events, such as methods annotated with @BeforeSuite, @AfterSuite, and other configuration annotations.
  • IAnnotationTransformer: Allows you to modify annotations at runtime. You can add or modify attributes of test annotations dynamically.
  • IReporter: Allows you to generate custom reports based on test results. You can create custom test execution reports with additional information.
By implementing these listener interfaces and overriding their respective methods, you can customize the behavior of TestNG during test execution. For example, you can log test results, perform cleanup tasks, handle test events, generate custom reports, and modify test configurations at runtime. Question: What are TestNG suites? Answer: In TestNG, a suite is a way to organize and execute a logical group of tests. It allows you to define a set of test classes or test methods that belong together and should be executed as a cohesive unit. TestNG suites provide a higher level of organization, allowing you to group related tests, configure test execution settings, and manage dependencies between test classes or methods. Question: How do you perform parameterization in TestNG, and what are the different ways to pass parameters to test methods? Answer: Parameterization allows you to pass data to test methods and execute them with different sets of input values. Parameterization is useful when you want to run the same test method with various combinations of data to test different scenarios or perform data-driven testing.

Using @Parameters Annotation:
@Test
@Parameters({ "username", "password" })
public void testLogin(String username, String password) {
    // Test login functionality using the provided username and password
}
testng.xml:
<suite name="MyTestSuite">
    <test name="Test1">
        <parameter name="username" value="user1" />
        <parameter name="password" value="pass123" />
        <classes>
            <class name="com.example.tests.ParameterizationExample" />
        </classes>
    </test>
</suite>
Question: Explain the concept of soft assertions in TestNG and how they differ from regular assertions. Answer: Soft assertions provide an alternative way of performing assertions compared to regular or hard assertions. The key difference lies in how they handle assertion failures and the continuation of test execution after an assertion failure occurs.

When a regular assertion, such as assertEquals or assertTrue, fails in TestNG, the test immediately stops at that assertion, and TestNG marks the test as failed.

Soft assertions, on the other hand, allow you to continue executing the test even after an assertion failure. This means all assertions can be checked, and the test is marked as failed when assertAll() is called if any of the soft assertions have failed.
@Test
public void testSoftAssertion() {
    int actualValue = 10;
    int expectedValue = 5;

    SoftAssert softAssert = new SoftAssert();

    softAssert.assertEquals(actualValue, expectedValue); // Assertion fails, but the test continues
    System.out.println("This line will be executed.");
    softAssert.assertAll(); // This will mark the test as failed if any soft assertion has failed
}

Question: How do you skip or ignore test methods selectively in TestNG, and what is the purpose of doing so? Answer: TestNG provides several ways to skip or ignore test methods selectively. This is useful when a test is temporarily unavailable, under development, not applicable to a particular execution, or should run only when a prerequisite test or group has been successfully executed.

1. Using the enabled Attribute:
@Test(enabled = false)
public void testMethod2() {
    // This test method will be skipped
}
2. Using dependsOnMethods or dependsOnGroups:
A test method can depend on another test method or group. If the required dependency does not successfully execute, the dependent test may be skipped by TestNG. Question: What are the different ways to specify test execution order in TestNG, and when would you use each method? Answer: TestNG provides several mechanisms for controlling or influencing test execution order.

1. Default Execution Order:
TestNG generally follows the order in which test classes and methods are discovered or specified. The exact order should not be relied upon when tests have no explicit ordering or dependency relationship.

2. Using the preserve-order Attribute:
The preserve-order attribute can be used in the TestNG XML configuration to preserve the order in which test classes are declared.
<suite name="MyTestSuite">
    <test name="Test1" preserve-order="true">
        <classes>
            <class name="com.example.tests.TestClass1" />
            <class name="com.example.tests.TestClass2" />
        </classes>
    </test>
</suite>
3. Using dependsOnMethods Attribute:
Use dependsOnMethods when one test method must execute after another test method and the second test should depend on the successful execution of the first.
@Test
public void testStep1() {
    // Test step 1 logic
}

@Test(dependsOnMethods = "testStep1")
public void testStep2() {
    // Test step 2 logic
}
4. Using Priority Attribute:
Use the priority attribute when you want to assign an execution priority to test methods. Lower priority values are executed before higher priority values.
@Test(priority = 1)
public void testStep1() {
    // Test step 1 logic
}

@Test(priority = 2)
public void testStep2() {
    // Test step 2 logic
}
Question: How can you create test dependencies in TestNG without using annotations? Answer: TestNG allows dependencies to be configured through testng.xml using group dependencies. Method-level dependencies, however, are normally defined using annotations or TestNG's programmatic APIs; they cannot be specified by simply adding a dependsOnMethods attribute to a testng.xml method entry.

1. Using testng.xml for Group Dependencies:
You can define dependencies between groups in the TestNG XML configuration.
<suite name="TestSuite">
    <test name="Test1">
        <groups>
            <dependencies>
                <group name="testMethod2" depends-on="testMethod1" />
            </dependencies>
        </groups>
        <classes>
            <class name="com.example.TestClass1" />
            <class name="com.example.TestClass2" />
        </classes>
    </test>
</suite>
For method-level dependencies, you can use dependsOnMethods in the @Test annotation.
import org.testng.annotations.Test;

public class TestClass1 {

    @Test
    public void testMethod1() {
        // Test method logic
    }
}

public class TestClass2 {

    @Test(dependsOnMethods = "testMethod1")
    public void testMethod2() {
        // Test method logic
    }
}
In this example, testMethod2 depends on testMethod1 because of the dependsOnMethods attribute. Question: How do you generate and analyze TestNG reports, and what information do these reports provide? Answer: TestNG generates reports after test execution, providing valuable information about test results and overall test suite execution. The generated reports commonly include HTML reports with details about test methods, pass/fail status, execution time, and other relevant information.

1. Run TestNG Tests:
First, execute your TestNG test suite. This can be done using various methods, such as running tests from the command line, an IDE, build tools such as Maven or Gradle, or continuous integration systems such as Jenkins.

2. Generate TestNG Reports:
After test execution, TestNG commonly generates HTML reports in the test-output folder by default. The reports provide an overview of the test results and detailed information about individual test methods.

3. Analyze TestNG Reports:
Open the generated HTML report in a web browser or HTML viewer to analyze the test results. The report can provide information such as:
  • Suite Summary: Shows information such as the total number of test cases, passed tests, failed tests, skipped tests, and execution time.
  • Test Details: Includes details for individual test methods, such as the test method name, test class name, status, and execution time.
  • Test Logs and Stack Traces: For failed test methods, TestNG can provide error messages and stack traces to help identify the cause of failure.
  • Configuration Methods: If configuration methods such as @BeforeTest or @BeforeClass are used, their execution results can be included in the report.
  • Groups and Parameters: TestNG reports can provide information about groups and parameters associated with test execution.
  • Time Taken: Execution times can help identify slow-running tests.
  • Custom Reports: If you implement a custom TestNG reporter using the IReporter interface, you can generate additional customized reports based on the test results.

Sunday, 27 August 2023

Selenium Question

Question: What is Selenium? 
Answer: Selenium is a widely used open-source automation framework primarily used for automating web applications. It provides a suite of tools that supports different aspects of test automation, including Selenium WebDriver, Selenium IDE, and Selenium Grid.
 
Question: Explain the difference between Selenium WebDriver and Selenium IDE. 
 Answer: Selenium WebDriver:

It is a powerful automation tool used for automating web applications by directly interacting with the browser. WebDriver provides a programming interface that allows automation scripts to be created and executed using various programming languages.

Selenium IDE:

It is a browser extension/add-on that supports record-and-playback functionality for creating and executing automation tests with minimal or no programming. Selenium IDE is available for browsers such as Chrome, Firefox, and Edge. 

Question: Explain Selenium Architecture. 
Answer: Selenium architecture consists of several important components that work together to automate web browsers.

Selenium Client Libraries:
  • Libraries are available for Java, Python, C#, Ruby, JavaScript, and other supported languages.
  • They allow automation scripts to be written using different programming languages.
W3C WebDriver Protocol:
  • Selenium 4 uses the W3C WebDriver standard for communication between Selenium client implementations and browser automation implementations.
  • The protocol defines standardized commands and responses for controlling web browsers.
Browser Drivers:
  • Browser drivers provide the WebDriver implementation used to communicate with specific browsers.
  • Examples include ChromeDriver, GeckoDriver, and EdgeDriver.
  • They act as an intermediary between Selenium automation code and the corresponding browser.
Browsers:
  • Chrome
  • Firefox
  • Microsoft Edge
  • Safari
WebDriver API:
  • The WebDriver API provides the programming interface used to automate web browsers.
  • It supports browser interactions such as clicking, typing, selecting, navigating, and interacting with web elements.
  • It is used through Selenium client libraries rather than being treated as a separate architectural component.
Selenium Server and Selenium Grid:
  • Selenium Server provides server-side functionality for remote WebDriver execution.
  • Selenium Grid enables remote and distributed test execution across multiple browsers and machines.
  • Grid is useful for parallel execution and cross-browser testing.

Question: What are the different types of locators supported by Selenium WebDriver?

Answer:

Selenium WebDriver supports the following types of locators for identifying web elements:

  • ID
  • Name
  • Class Name
  • Tag Name
  • Link Text
  • Partial Link Text
  • CSS Selector
  • XPath

Question: What is the WebDriver interface in Selenium?

Answer:

The WebDriver interface in Selenium represents an object that allows interaction with a web browser. It provides methods for:

  • Launching a browser.
  • Navigating to URLs.
  • Interacting with web elements.
  • Managing browser windows and tabs.
  • Controlling browser behavior.

Question: How do you handle frames and iframes in Selenium WebDriver?

Answer:

Selenium WebDriver provides the switchTo().frame() method to switch the driver's focus to a frame or iframe so that elements inside it can be accessed and interacted with.

Example: Switch to a frame using its name or ID.

driver.switchTo().frame("frameName");

Example: Switch to a frame using its index.

driver.switchTo().frame(0);

Example: Switch to a frame using a WebElement.

WebElement frame = driver.findElement(By.id("frameId"));
driver.switchTo().frame(frame);

Example: Return to the main page.

driver.switchTo().defaultContent();

Note: You must switch to the appropriate frame before interacting with elements inside it. Use defaultContent() to return to the main page and parentFrame() to move to the parent frame.


Question: Difference between findElement() and findElements().

Answer:

findElement()

  • Returns the first matching web element.
  • Throws NoSuchElementException if no matching element is found.
  • Used when only one element is expected.

findElements()

  • Returns a list of all matching web elements.
  • Returns an empty list if no matching elements are found.
  • Does not throw an exception when no elements exist.
  • Used when multiple matching elements are expected.

Note: findElement() throws an exception when no element is found, whereas findElements() returns an empty list.


Question: Relative Locators in Selenium 4.

Answer:

Selenium 4 introduced Relative Locators, allowing elements to be located based on their position relative to other elements instead of relying only on traditional locators.

Relative Locator Methods:

  • above() – Locates an element above the specified element.
  • below() – Locates an element below the specified element.
  • toLeftOf() – Locates an element to the left of the specified element.
  • toRightOf() – Locates an element to the right of the specified element.
  • near() – Locates an element within approximately 50 pixels of the specified element. You can also specify a custom distance.

Example: Using Relative Locators.

@Test
public void testOne() {

    String id = driver.findElement(
            withTagName("li")
                    .toLeftOf(By.id("ppid6"))
                    .below(By.id("ppid1"))
    ).getAttribute("id");

    assertEquals(id, "ppid5");
}

Note: Relative locators improve the readability of test scripts and are especially useful when traditional locators are difficult to maintain.

Question: Better Window Tab Management in Selenium 4

Answer:

newWindow() allows users to create and switch to a new browser window or tab without creating a new WebDriver instance.

Example: Open a new browser window.

driver.get("https://www.google.com/");

// Opens a new window and switches to it
driver.switchTo().newWindow(WindowType.WINDOW);

// Opens Facebook in the newly created window
driver.navigate().to("https://www.fb.com/");

Example: Open a new tab in the same browser window.

driver.get("https://www.google.com/");

// Opens a new tab
driver.switchTo().newWindow(WindowType.TAB);

// Opens Facebook in the newly opened tab
driver.navigate().to("https://www.fb.com/");

Note: WindowType.WINDOW creates a completely new browser window, whereas WindowType.TAB opens a new tab in the existing browser window.


Question: Selenium 4 - Modifications in the Actions Class

Answer: The Actions class is used to perform advanced mouse and keyboard interactions. Selenium 4 introduced overloaded methods that accept a WebElement directly, reducing the need for moveToElement().

Important: These methods make the code cleaner, easier to read, and more efficient.

click(WebElement)

Clicks directly on the specified element.

actions.click(element).perform();

clickAndHold(WebElement)

Clicks and holds the left mouse button on an element.

actions.clickAndHold(element).perform();

contextClick(WebElement)

Performs a right-click on the specified element.

actions.contextClick(element).perform();

doubleClick(WebElement)

Performs a double-click operation.

actions.doubleClick(element).perform();

release()

Releases the pressed mouse button.

actions.release().perform();

Question: Methods for Operations on Select Drop-down

Answer: The Select class provides methods for selecting and deselecting options from a drop-down list.

Example: Create a Select object.

Select select = new Select(element);

Example: Common Select methods.

select.selectByIndex(index);

select.selectByVisibleText("Text");

select.selectByValue("Value");

select.deselectAll();

select.deselectByIndex(index);

select.deselectByVisibleText("Text");

select.deselectByValue("Value");

List options = select.getOptions();

Note: The deselect methods work only with multi-select drop-downs.

Question: Actions in Selenium

Answer: 

Actions class in Selenium WebDriver is used for performing advanced user interactions like drag-and-drop, double-click, mouse hover, etc., which cannot be achieved using simple interactions.


Program:

Actions action = new Actions(driver);

action.keyDown(Keys.CONTROL);

action.keyUp(Keys.CONTROL);

action.clickAndHold(webElement).build().perform();

action.doubleClick(webElement).build().perform();

action.moveToElement(webElement).build().perform();

action.moveByOffset(xOffset,yOffset).build().perform();

action.dragAndDrop(sourceEle,targetEle).build().perform();

action.release().build().perform();

Question: Alert Handling in Selenium Answer: To handle alerts, you can use Alert interface methods like accept(), dismiss(), and getText(). Use driver.switchTo().alert() to switch to the alert context before interacting with it. Program: // Switching to Alert Alert alert = driver.switchTo().alert(); // Capturing alert message. String message= driver.switchTo().alert().getText(); // Accepting alert alert.accept(); // To click on the ‘Cancel’ button of the alert. driver.switchTo().alert().dismiss(); //sendKeys driver.switchTo().alert().sendKeys("Text"); Question: Window Handling in Selenium Answer: To handle multiple windows or tabs, you can use the windowHandles() method to switch between them. First, use getWindowHandle() to get the handle of the current window, and then use switchTo().window() to switch between different windows or tabs. Example: Driver.getWindowHandles(); Driver.getWindowHandle(); Program: { String mainWindow=driver.getWindowHandle(); Set<String> allWindows =driver.getWindowHandles(); Iterator<String> ii=allWindows.iterator(); while(ii.hasNext()) { String childWindow=ii.next(); if(!mainWindow.equalsIgnoreCase(childWindow)) { // Switching to Child window driver.switchTo().window(childWindow); //TODO // Closing the Child Window. driver.close(); } } // Switching to Parent window i.e Main Window. driver.switchTo().window(MainWindow); } Question: Desired Capabilities Answer:

Desired Capabilities in Selenium is a set of key-value pairs used to configure and customize the behavior of a web browser during test automation.

It allows testers to specify various settings and preferences for the browser session, such as browser name, version, platform, and other specific properties.

Program: DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer(); capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE"); capabilities.setCapability(InternetExplorerDriver. INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); Question: Screenshot in Selenium Answer: You can capture screenshots in Selenium using the getScreenshotAs() method. Screenshots are valuable for debugging, documentation, and reporting when a test case fails or encounters an issue. Program: //Convert web driver object to TakeScreenshot TakesScreenshot scrShot =((TakesScreenshot)webdriver); //Call getScreenshotAs method to create image file File srcFile= scrShot.getScreenshotAs(OutputType.FILE); File destFile=new File(file_path); FileUtils.copyFile(srcFile, destFile); Question: What are the differences between Selenium WebDriver and Selenium Grid? Answer: Selenium WebDriver is used for automating tests on a single machine and browser, whereas Selenium Grid is used for distributed test execution on multiple machines and browsers in parallel. Question: Explain the concept of dynamic XPath in Selenium. How do you create dynamic XPath expressions? Answer: Dynamic XPath expressions are used to locate elements that may change based on attributes or positions. You can create dynamic XPath expressions by using functions like contains(), starts-with(), and position(), along with placeholders for changing attributes. Question: What is a WebElement in Selenium, and how is it different from a WebDriver? Answer: A WebElement represents an HTML element on a web page. It is used to interact with web page elements. WebDriver is used for browser automation and controls the browser instance. Question: What is the difference between close() and quit() methods in Selenium WebDriver? Answer: The close() method closes the current browser window or tab, while the quit() method closes the entire WebDriver session, including all open windows or tabs. Question: SSL Certificate in Firefox Answer: Program: ProfilesIni prof = new ProfilesIni() FirefoxProfile ffProfile= prof.getProfile ("myProfile") ffProfile.setAcceptUntrustedCertificates(true) ffProfile.setAssumeUntrustedCertificateIssuer(false) WebDriver driver = new FirefoxDriver (ffProfile) Note: “setAcceptUntrustedCertificates” and “setAssumeUntrustedCertificateIssuer“ are capabilities to handle the certificate errors in web browsers. Example: SSL Certificate Error Handling in Chrome Program: DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome () handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true) WebDriver driver = new ChromeDriver (handlSSLErr); Example: SSL Certificate Error Handling in IE Program: 1. driver.navigate ().to ("javascript:document.getElementById('overridelink').click()"); 2. DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); System.setProperty("webdriver.ie.driver","IEDriverServer.exe"); WebDriver driver = new InternetExplorerDriver(capabilities); Question: JavaScriptExecutor in Selenium Answer: Program: JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script, Arguments); Program: js.executeScript("window.scrollBy(0,600)"); // scroll down js.executeScript("window.scrollBy(0,1000)"); js.executeScript("arguments[0].scrollIntoView();", Element); Question: Cookies in Selenium Answer: Program: driver.manage().getCookies(); //Return The List of all Cookies driver.manage().getCookieNamed(arg0); //Return specific cookie according to name driver.manage().addCookie(arg0); //Create and add the cookie driver.manage().deleteCookie(arg0); //Delete specific cookie driver.manage().deleteCookieNamed(arg0); //Delete specific cookie according Name driver.manage().deleteAllCookies(); //Delete all cookies Question: Action - Drag and Drop in selenium Answer: Program: Actions.dragAndDrop(Sourcelocator, Destinationlocator) Actions.dragAndDropBy(Sourcelocator, x-axis pixel of Destinationlocator, y-axis pixel of Destinationlocator) Question: Implicit Wait Answer:Implicit Wait is a concept in Selenium that allows you to set a global timeout for the WebDriver instance.
When an implicit wait is applied, the WebDriver will wait for a certain amount of time before throwing a "NoSuchElementException" if an element is not immediately found on the web page. Note: The purpose of using an Implicit Wait is to avoid immediate failure of test scripts due to synchronization issues with the web application.
It provides some breathing space for the elements to load or become available on the page before attempting to interact with them. Program: driver.manage().timeouts() .implicitlyWait(Duration.ofSeconds(10)); driver.manage().timeouts() .pageLoadTimeout(Duration.ofSeconds(10)); Question: Explicit Wait in Selenium Answer: Explicit Wait is another synchronization technique in Selenium that allows you to specify a condition or set of conditions to wait for, rather than a global wait like the Implicit Wait. It gives you more control and flexibility over the waiting behavior, allowing you to wait for specific elements to meet certain conditions before proceeding with test execution. Program: new WebDriverWait(driver, Duration.ofSeconds(3)) .until(ExpectedConditions .elementToBeClickable(By.cssSelector("#id"))); Program: alertIsPresent() elementSelectionStateToBe() elementToBeClickable() elementToBeSelected() frameToBeAvaliableAndSwitchToIt() invisibilityOfTheElementLocated() invisibilityOfElementWithText() presenceOfAllElementsLocatedBy() presenceOfElementLocated() textToBePresentInElement() textToBePresentInElementLocated() textToBePresentInElementValue() titleIs() titleContains() visibilityOf() visibilityOfAllElements() visibilityOfAllElementsLocatedBy() visibilityOfElementLocated() Question: Fluent Wait in Selenium Answer: Fluent Wait is a specialized form of Explicit Wait in Selenium that allows you to define the maximum amount of time to wait for a certain condition to be true while also specifying the polling interval.
The polling interval is the frequency at which WebDriver checks for the expected condition to be met.
The Fluent Wait is helpful when dealing with dynamic web applications where elements may take some time to load or change state.
It allows you to wait for elements to become available or change without the need for specifying an exact timeout. Program: Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class); Question: Exception Handling in Selenium Answer: 1. ElementNotVisibleException: This type of Selenium exception occurs when an existing element in DOM has a feature set as hidden.
2. ElementNotSelectableException: This Selenium exception occurs when an element is presented in the DOM, but you can be able to select. Therefore, it is not possible to interact.
3. NoSuchElementException: This Exception occurs if an element could not be found.
4. NoSuchFrameException: This Exception occurs if the frame target to be switched to does
5. NoSuchWindowException: This Exception occurs if the window target to be switch does not exist.
6. StaleElementReferenceException: This Selenium exception occurs happens when the web element is detached from the current DOM.
7. SessionNotFoundException: The WebDriver is acting after you quit the browser.
8. TimeoutException: Thrown when there is not enough time for a command to be completed. For Example, the element searched wasn’t found in the specified time.
9. WebDriverException: This Exception takes place when the WebDriver is acting right after you close the browser.
11. ConnectionClosedException: This type of Exception takes place when there is a disconnection in the driver.
12. ElementClickInterceptedException: The command may not be completed as the element receiving the events is concealing the element which was requested clicked.
13. ElementNotInteractableException: This Selenium exception is thrown when any element is presented in the DOM. However, it is impossible to interact with such an element.
14. ErrorInResponseException: This happens while interacting with the Firefox extension or the remote driver server.
15. ErrorHandler.UnknownServerException: Exception is used as a placeholder in case if the server returns an error without a stack trace.
16. ImeActivationFailedException: This expectation will occur when IME engine activation has failed.
17. ImeNotAvailableException: It takes place when IME support is unavailable.
18. InsecureCertificateException: Navigation made the user agent to hit a certificate warning. This can cause by an invalid or expired TLS certificate.
19. InvalidArgumentException: It occurs when an argument does not belong to the expected type.
20. InvalidCookieDomainException: This happens when you try to add a cookie under a different domain instead of current URL.
21. InvalidCoordinatesException: This type of Exception matches an interacting operation that is not valid.
22. InvalidElementStateException: It occurs when command can’t be finished when the element is invalid.
23. InvalidSessionIdException: This Exception took place when the given session ID is not included in the list of active sessions. It means the session does not exist or is inactive either.
24. InvalidSwitchToTargetException: This occurs when the frame or window target to be switched does not exist.
25. JavascriptException: This issue occurs while executing JavaScript given by the user.
26. JsonException: It occurs when you afford to get the session when the session is not created.
27. NoSuchAttributeException: This kind of Exception occurs when the attribute of an element could not be found.
28. MoveTargetOutOfBoundsException: It takes place if the target provided to the ActionChains move() methodology is not valid. For Example, out of the document.
29. NoSuchContextException: ContextAware does mobile device testing.
30. NoSuchCookieException: This Exception occurs when no cookie matching with the given pathname found for all the associated cookies of the currently browsing document.
31. NotFoundException: This Exception is a subclass of WebDriverException. This will occur when an element on the DOM does not exist.
32. RemoteDriverServerException: This Selenium exception is thrown when the server is not responding because of the problem that the capabilities described are not proper.
33. ScreenshotException: It is not possible to capture a screen.
34. SessionNotCreatedException: It happens when a new session could not be successfully created.
35. UnableToSetCookieException: This occurs if a driver is unable to set a cookie.
36. UnexpectedTagNameException: Happens if a support class did not get a web element as expected.
37. UnhandledAlertException: This expectation occurs when there is an alert, but WebDriver is not able to perform Alert operation.
38. UnexpectedAlertPresentException: It occurs when there is the appearance of an unexpected alert.
39. UnknownMethodException: This Exception happens when the requested command matches with a known URL but and not matching with a methodology for a specific URL.
40. UnreachableBrowserException: This Exception occurs only when the browser is not able to be opened or crashed because of some reason.
41. UnsupportedCommandException: This occurs when remote WebDriver doesn’t send valid commands as expected.
Question: Advanced Browser Configuration Answer: Program: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--ignore-certificate-errors"); chromeOptions.addArguments("user-data-dir=Path"); chromeOptions.addArguments("--headless"); chromeOptions.addArguments("--start-maximized", "--incognito","--disable-notifications" ); driver = new ChromeDriver(chromeOptions); Content: --start-maximized: Opens Chrome in maximize mode
--incognito: Opens Chrome in incognito mode
--headless: Opens Chrome in headless mode
--disable-extensions: Disables existing extensions on Chrome browser
--disable-popup-blocking: Disables pop-ups displayed on Chrome browser Question: Elements Operations Answer: WebElement element = driver.FindElement(By.id("id")); Program: element.click(); element.sendKeys("Input Text"); element.clear(); element.submit(); element.getAttribute(“type”); String text = element.getText(); boolean enabledStatus = element.isEnabled(); boolean displayedstatus = element.isDisplayed(); boolean selectedstatus = element.isSelected(); Question: Methods for Navigation Answer: Program: driver.get("url"); driver.manage().window().maximize(); driver.manage().window().fullscreen(); driver.navigate().to("url"); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); driver.close(); driver.quit(); Question: Difference between Implicit & Explicit wait? Answer: Implicit waits set a global timeout for all elements, while explicit waits are used for specific elements and conditions.
You would use implicit waits when you want to apply a timeout for every element, and explicit waits when you want to wait for specific conditions for a particular element.

Scope:
Implicit Wait: It is a global wait applied once when the WebDriver instance is created. It applies to all find element calls throughout the test script until changed or disabled.
Explicit Wait:It is a more specific wait applied to a particular element or a certain condition. It allows you to wait for a specific condition to be met for a particular element only.
Usage:
Implicit Wait:It is generally used to handle basic synchronization issues. It is applied globally to all elements in the test script, which can be useful when elements take some time to appear or load.
Explicit Wait:It is used for more complex synchronization scenarios. It is applied only to specific elements or conditions where you need to wait for specific actions or changes to occur.
Granularity:
Implicit Wait: It is less granular since it is a global setting and is not focused on a specific element or condition.
Explicit Wait: It is more granular since it can be applied to specific elements or conditions, allowing you to have more control over the wait time and the expected conditions.
Condition Checking:
Implicit Wait: It waits for a fixed amount of time before throwing a NoSuchElementException if an element is not found.
Explicit Wait: It waits for a specific condition to be met within a given timeout. The condition can be based on the presence, visibility, clickability, etc., of an element or any custom condition you define. Question: Explain StaleElementReferenceException Answer: StaleElementReferenceException is a common exception that occurs in Selenium when you try to interact with an element on a web page, but the element reference becomes "stale" or no longer valid.
A stale element reference means that the element you were interacting with has been deleted or changed on the page, making the reference to that element invalid.
This exception typically occurs in the following scenarios:
DOM Changes: The element you are trying to interact with is part of the DOM (Document Object Model), and there is a dynamic change to the DOM that causes the element to be removed or replaced.
Page Navigation: If you navigate away from the page and then return to it, any references to elements from the previous page will become stale.
Asynchronous Actions: If there are asynchronous actions on the page that modify the DOM, the element references can become stale.

To handle StaleElementReferenceException, you can use one of the following strategies:

Retry Mechanism: Implement a retry mechanism to attempt the action again.
You can use a loop with a try-catch block to retry the action a few times before giving up. Refresh the Element Reference:
If you encounter a stale element reference, re-find the element using appropriate locators to get a fresh reference to the element. Question: User Defined Exception Answer: User Defined Exception or custom exception is creating your own exception class and throws that exception using 'throw' keyword.
This can be done by extending the class Exception.
The keyword “throw” is used to create a new Exception and throw it to the catch block. Question: Apart from sendkeys, are there any different ways, to type content onto the editable field? Answer: Program: WebDriver driver = new FirefoxDriver(); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("document.getElementById("textbox_id") .value = 'new value';); Question: Difference between Actions and Action Answer: Actions is a class that is based on a builder design pattern. This is a user-facing API for emulating complex user gestures.
Whereas Action is an Interface which represents a single user-interaction action. Question: Framework in selenium Answer: Module-Based Testing Framework: Also known as a modular testing framework, this approach involves breaking down the application under test into smaller, manageable modules.
Test cases are then created to verify the functionality of each module independently. This framework promotes reusability and maintainability of test scripts.

Data-Driven Testing Framework: In this framework, test data is separated from test scripts. Test cases are designed to read input data from external sources such as Excel sheets, CSV files, or databases.
By decoupling test data from test logic, data-driven testing allows for easy maintenance and scalability.

Keyword-Driven Testing Framework: Also referred to as table-driven testing or action-word testing, this framework abstracts test scripts from the actual test steps by using keywords or actions to represent test actions.
Test cases are created in a tabular format where each row corresponds to a test step.
This approach enhances readability and enables testers with limited programming knowledge to create and maintain tests.

Hybrid Testing Framework: This framework combines the features of multiple frameworks such as data-driven, keyword-driven, and modular frameworks to leverage their respective advantages.
It provides flexibility in test design by allowing testers to choose the most appropriate approach based on the requirements of each test case.

Behavior-Driven Development (BDD) Framework: BDD frameworks like Cucumber or SpecFlow focus on collaboration between technical and non-technical stakeholders by using a domain-specific language (DSL) to describe application behavior in a human-readable format.
Tests are written in a structured format using Given-When-Then syntax, promoting better communication and understanding between team members.

Page Object Model (POM): POM is not a separate framework but rather a design pattern that promotes the creation of reusable and maintainable code in Selenium tests.
It involves creating a separate class for each web page or component of the application, encapsulating the page's elements and actions within the corresponding class. POM enhances code maintainability and reduces code duplication by centralizing element locators and page interactions.

TestNG Framework: TestNG is a testing framework for Java that can be integrated with Selenium WebDriver to perform various testing activities such as parameterization, parallel execution, grouping of test cases, and generating test reports.
It provides annotations for defining test methods, setup, and teardown methods, making it easier to organize and execute tests.

Question: Page Object Model (POM) Framework Answer: The typical workflow in the Page Object Model framework involves creating Page Object Classes for each web page or application screen, defining element locators and action methods within those classes, and using these classes in the test scripts to interact with the web elements.

Page Object Class:
In POM, each web page or application screen is represented as a separate Java class. This class is referred to as the "Page Object Class." It contains methods and elements related to that specific page.
Element Locators:
Element locators (such as IDs, names, XPaths, or CSS selectors) are defined within the Page Object Class. These locators identify the web elements on the page, such as buttons, text fields, and links.
Action Methods:
Action methods are defined in the Page Object Class to interact with the web elements. These methods encapsulate the user actions, such as clicking a button, entering text, or selecting options from dropdowns.
Page Navigation:
The Page Object Model also includes methods for navigating between different pages or application screens. For example, going from the login page to the home page.
Separation of Concerns:
POM promotes the separation of concerns by keeping the test logic (test scripts) separate from the UI logic (Page Object Classes). This separation ensures that changes to the UI do not impact the test scripts.
Code Reusability:
The Page Object Model enables code reusability by providing reusable Page Object Classes. The same Page Object Classes can be used in multiple test cases.
Easy Maintenance:
POM improves the maintainability of the test code as UI changes can be addressed within the corresponding Page Object Classes without affecting the entire test suite. Readability and Understandability:
By using descriptive names for methods in Page Object Classes, the test scripts become more readable and self-explanatory, making them easier to understand.
Page Factory in Selenium is an inbuilt Page Object Model framework concept for Selenium WebDriver but it is very optimized.
It is used for initialization of Page objects or to instantiate the Page object itself.
It is also used to initialize Page class elements without using “FindElement/s.
@FindBy can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as attributes. Program: @FindBy(name="uid") WebElement userName; @FindBy(name="password") WebElement passWord; @FindBy(className="cone") WebElement titleText; Question: How do you handle synchronization issues in Selenium WebDriver Answer: Handling synchronization issues is essential in Selenium WebDriver to ensure that test scripts interact with web elements at the right time, especially when the application's response time is unpredictable or elements take time to load.
Synchronization is critical to avoid test failures due to element not found or stale element references. Below are some techniques.

1.Implicit Wait
2.Explicit Wait
3.Fluent Wait
4.Thread.sleep
Question: What is Cross-Browser Testing, and how can you achieve it using Selenium WebDriver Answer: Cross-browser testing is the process of testing a web application or website across multiple web browsers to ensure consistent functionality and appearance across different browser environments.
As different browsers may interpret and render web pages differently, cross-browser testing helps identify any compatibility issues that might affect the user experience.

After setting up WebDriver instances for different browsers, you can execute your test scripts across multiple browsers by changing the driver initialization. Example: For example, you can switch from Chrome to Firefox:
Content: Selenium WebDriver allows you to achieve cross-browser testing by leveraging its ability to automate interactions with various web browsers. Question: How do you integrate Selenium with Jenkins Answer: Jenkins is a continuous integration server that automates the build, test, and deployment processes.

To integrate Selenium with Jenkins, follow these steps:
1. Set up a Jenkins server and install the necessary plugins (e.g., Maven Integration Plugin, TestNG Plugin).
2. Create a Jenkins job for your Selenium test project.
3. Configure the Jenkins job to fetch the source code from your version control system (e.g., Git, SVN).
4. Set up build triggers, such as polling the version control system for changes or executing on a schedule.
5. Configure the build to use Maven for building and executing the Selenium tests.
6. Integrate the TestNG test reports with Jenkins using the TestNG Plugin.
Question: How do you handle dynamic web elements that have changing locators during test automation? Answer: Dynamic locators are elements whose attributes (like ID, name, XPath, etc.) change frequently, making it difficult to identify and interact with them consistently.
Here are some strategies to handle dynamic web elements during test automation using Selenium WebDriver:

1. Use Stable Locators - Whenever possible, try to identify and use stable locators that are less likely to change over time.
2. CSS Selectors or XPath Axes - identify elements based on their relationship with other stable elements. For example, you can use "parent-child" or "sibling" relationships to locate dynamic elements based on their context
3. Relative XPath or CSS Selectors
4. Dynamic Attributes - identify patterns in the dynamic attribute values and use partial matches or regular expressions to locate the elements.
5. Explicit Waits
6. Page Refresh - In some cases, the dynamic elements may become stable after a page refresh.
7. Using JavaScript - In extreme cases, use JavaScript to locate elements by evaluating their dynamic properties directly in the DOM.
Question: Can you describe a complex testing challenge you faced in your previous role and how you overcame it? Answer: I have experience with several test automation frameworks, including TestNG, JUnit, and Cucumber.
The choice of framework depends on project requirements. For example, in a data-driven testing scenario,
I prefer TestNG for its built-in support for parameterization.
In projects with behavior-driven development (BDD) requirements, I've used Cucumber for its natural language support and collaboration capabilities with non-technical stakeholders.

Question: Describe your process for designing and maintaining automated test suites. How do you ensure scalability and maintainability of your test scripts? Answer: My approach to test suite design starts with a clear understanding of the application's architecture and the use of Page Object Model (POM).

I create reusable components and libraries to minimize redundancy. Test data is externalized to separate files or databases to ensure flexibility.

Regular code reviews and refactoring sessions help maintain script quality, and version control systems are used to track changes.
Question: Have you integrated your automated tests with Continuous Integration (CI) and Continuous Deployment (CD) pipelines? If so, which CI/CD tools have you used? Answer: Yes, I have integrated automated tests into CI/CD pipelines using tools like Jenkins, Travis CI, and GitLab CI/CD.

This integration ensures that tests are automatically triggered upon code changes and that deployments occur smoothly after successful testing.

It also helps maintain a culture of continuous testing and quality assurance throughout the development process.

Question: Can you describe a complex testing challenge you faced in your previous role and how you overcame it? Answer: Certainly. In my previous role, we had a large-scale e-commerce platform with a complex pricing engine.
One of the challenges was testing the dynamic pricing algorithm, which had numerous variables and dependencies.

To address this, I collaborated closely with the development team to understand the logic behind the pricing engine. We created extensive test data sets covering various scenarios and edge cases.
We also automated the testing process to execute a wide range of tests quickly. This allowed us to identify and resolve pricing inconsistencies efficiently.

Question: What strategies do you use to achieve test data independence and maintain test data integrity in your automation framework? Answer: Test data independence ensures that test cases are not tightly coupled to specific test data, allowing them to be reusable and maintainable.
Test data integrity ensures that the test data used in the automation process remains accurate and consistent.
Here are some strategies to achieve these goals:

1. Data-Driven Testing
2. Parameterization - Use TestNG's @DataProvider or JUnit's @ParameterizedTest annotations to supply test data
3. Random Test Data Generation - For non-sensitive data, consider generating random test data using libraries or utilities.
4. Data Setup and Teardown
5. Isolation and Sandbox Environments -Utilize isolated environments or sandboxes for test data that replicates the production environment but does not impact the production data. This ensures test data integrity without affecting the live data
6. Data Encryption and Decryption - For sensitive data, use encryption techniques when storing test data in external sources. Decrypt the data during test execution to ensure data security and integrity
7. Database Backup and Restore - Before executing automated tests that involve database interactions, create a backup of the database, and restore it after the test run. This guarantees that the database remains unaffected by test activities
8. Data Versioning - Implement version control for test data to track changes over time and ensure data integrity. Store different versions of test data and associate them with specific test executions
9. Test Data Refresh: - Periodically refresh the test data to keep it up-to-date and relevant for the current testing needs. This prevents test data from becoming stale and unreliable.
10. Separate Test Data from Configuration: - Keep test data separate from configuration settings to prevent accidental changes to the data while updating configuration parameters.
Data Verification: - Implement data verification checks within test scripts to ensure that the data used during test execution is accurate and matches the expected state.
Question: How do you handle large test suites in Selenium to optimize execution time and reduce maintenance efforts? Answer: Handling large test suites in Selenium efficiently is essential to optimize execution time and reduce maintenance efforts.
Here are some strategies to achieve this:


1. Test Suite Segregation:
- Divide the large test suite into smaller logical test suites based on functional areas or test scenarios. This allows you to run smaller subsets of tests when needed, reducing execution time.
2. Parallel Execution:
- Implement parallel test execution to execute multiple tests simultaneously, reducing overall execution time. TestNG provides built-in support for parallel execution, allowing tests to run concurrently.
3. Selective Test Execution:
- Implement test groups or tags to categorize tests based on priority, functionality, or criticality. Use TestNG's `groups` attribute or TestNG XML configuration to execute specific test groups as needed.
4. Data-Driven Testing:
- Utilize data-driven testing to execute multiple test iterations using different test data. This helps in expanding test coverage without creating separate test cases for each data set.
5. Page Object Model (POM):
- Implement the Page Object Model design pattern to separate test scripts from the page-specific methods and locators. This enhances code reusability and reduces maintenance efforts.
6. Data Setup and Teardown:
- Optimize data setup and teardown processes to ensure that each test is independent of others. Use transactions or rollback mechanisms to revert changes made during tests, keeping the data in a consistent state.
7. Test Dependencies and Ordering:
- Use TestNG's dependency feature to manage the order of test execution and ensure that certain tests run before others. Carefully define test dependencies to prevent redundant setups and teardowns.
8. Smart Waiting:
- Use explicit waits judiciously to avoid excessive waiting during test execution. Smartly define wait conditions to ensure that the test proceeds as soon as the element becomes available, minimizing execution time.
9. Headless Browsers:
- Consider using headless browsers like headless Chrome or headless Firefox for faster execution, especially for tests that do not require visual verification.
10. Continuous Integration (CI):
- Integrate the test suite with a CI server (e.g., Jenkins, Travis CI) to automate test execution on every code commit or scheduled intervals. CI helps identify issues early and reduces manual intervention.
11. Test Result Analysis:
- Analyze test results regularly to identify flaky tests or tests that consume excessive time. Address and fix flaky tests to ensure consistent and reliable test results.
12. Test Suite Maintenance:
- Regularly review and update the test suite by removing obsolete or redundant tests. This ensures that the test suite remains lean and focused on critical functionality.
Question: How do you perform API testing alongside Selenium test automation? Describe the tools or frameworks you've used for API testing. Answer: Performing API testing alongside Selenium test automation is essential for comprehensive testing of web applications.
API testing focuses on verifying the functionality and responses of API endpoints, while Selenium test automation verifies the web application's user interface.

Postman: Postman is a user-friendly API testing tool that allows you to create and execute API requests, analyze responses, and automate API testing workflows.
RestAssured: RestAssured is a Java-based library specifically designed for API testing. It provides a simple and expressive syntax for writing API tests in Java.
SoapUI: SoapUI is a comprehensive API testing tool that supports both REST and SOAP APIs. It offers a graphical user interface for test creation and execution.
Insomnia: Insomnia is a powerful API testing tool with features like request/response inspection, authentication, and data-driven testing.
Question: Handle authentication pop-ups in Selenium Answer: 1. Basic Authentication Pop-ups: Program: String username = "yourUsername"; String password = "yourPassword"; String urlWithCredentials = "http://" + username + ":" + password + "@example.com"; driver.get(urlWithCredentials); Content: 2. Alert Authentication Pop-ups:
When a pop-up is displayed using JavaScript's window.alert(), window.confirm(), or window.prompt(), you can use the Alert interface to handle it. Program: Alert alert = driver.switchTo().alert(); alert.authenticateUsing(new UserAndPassword(username, password)); Content: HTTP Basic Authentication Pop-ups: Some websites use HTTP Basic Authentication, which involves sending an HTTP request with the "Authorization" header containing the encoded credentials.
You can use Selenium to automate this: Program: String username = "yourUsername"; String password = "yourPassword"; String url = "http://example.com/protected-resource"; Example: Create an instance of DesiredCapabilities to set the credentials Program: DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.SUPPORTS_ALERTS, true); capabilities.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true); Example: Encode the credentials and set them in the request header Program: String authString = username + ":" + password; String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes()); capabilities.setCapability(CapabilityType.PAGE_LOAD_STRATEGY, "none"); capabilities.setCapability(CapabilityType.PROXY, getProxy(encodedAuthString)); WebDriver driver = new FirefoxDriver(capabilities); driver.get(url); Question: What is WebDriverFactory, and why would you use it in your Selenium automation framework Answer: A `WebDriverFactory` is a design pattern or utility class used in Selenium automation frameworks to create and manage instances of WebDriver, which is the interface used to interact with web browsers in Selenium. It provides a centralized mechanism for WebDriver instantiation, configuration, and management within your automation framework. Here's why you would use a `WebDriverFactory` in your Selenium automation framework:

1. Abstraction of WebDriver Creation: A `WebDriverFactory` abstracts the creation of WebDriver instances. Instead of instantiating WebDriver directly in your test scripts, you call methods provided by the factory to create WebDriver instances. This abstraction simplifies test script development and makes your code more maintainable.
2. Configuration Management: You can use the `WebDriverFactory` to manage WebDriver configurations in one place. This includes setting browser-specific options, handling different browser versions, and managing timeouts. This centralized configuration management ensures consistency across your test suite.
3. Support for Multiple Browsers: With a `WebDriverFactory`, you can easily switch between different web browsers (e.g., Chrome, Firefox, Edge) without modifying your test scripts extensively. The factory can handle the logic of selecting and initializing the appropriate WebDriver based on the desired browser choice.
4. Parallel Test Execution: When running tests in parallel, a `WebDriverFactory` can help manage thread safety and ensure that each thread gets its isolated WebDriver instance. This prevents conflicts and ensures that tests can run concurrently without interference.
5. Reusable Code: By encapsulating WebDriver instantiation and configuration logic within a `WebDriverFactory`, you promote code reuse. Multiple test scripts and test cases can leverage the factory, reducing duplication of code and making maintenance easier.
6. Error Handling and Logging: A well-designed `WebDriverFactory` can include error handling and logging mechanisms. It can catch exceptions related to WebDriver initialization and provide detailed logs, making it easier to diagnose and troubleshoot issues during test execution.
7. Cleaner Test Scripts: Test scripts become more concise and focused on test logic when WebDriver creation and setup details are abstracted away. This results in cleaner, more readable, and more maintainable test scripts.
Here's a simplified example of how a `WebDriverFactory` might be implemented in Java:
Program: public class WebDriverFactory { public static WebDriver createWebDriver(BrowserType browserType) { WebDriver driver = null; switch (browserType) { case CHROME: // Configure and create a ChromeDriver instance break; case FIREFOX: // Configure and create a FirefoxDriver instance break; // Add support for other browsers as needed } return driver; } // Additional methods for setting up WebDriver options, timeouts, etc. } Note: In your test scripts, you would use the `WebDriverFactory` as follows: Program: WebDriver driver = WebDriverFactory.createWebDriver(BrowserType.CHROME); driver.get("https://example.com"); // Perform test actions using the WebDriver instance driver.quit(); Important: By using a `WebDriverFactory`, you can streamline your test automation process, improve code maintainability, and enhance the flexibility of your automation framework to support various browsers and configurations. Question: What do you mean by ROI in Selenium Answer: In the context of Selenium and software testing, "ROI" typically stands for "Return on Investment." ROI is a measure of the value or benefit that an organization or individual gains from an investment compared to the cost of that investment.

In the context of Selenium and test automation, calculating ROI involves evaluating whether the benefits of implementing Selenium testing (automation) outweigh the costs associated with developing and maintaining the automated test suite. Here are some factors to consider when assessing the ROI of Selenium automation:

1. Time Savings: Automated tests can execute much faster than manual tests. This can lead to significant time savings in the long run, especially when you have a large and complex application that requires frequent testing.
2. Reusability: Automated test scripts can be reused for regression testing across different versions of the software. This reusability can save time and effort compared to manual testing, where tests would need to be repeated from scratch.
3. Consistency: Automated tests can consistently perform the same actions and verifications, reducing the risk of human error in repetitive testing tasks.
4. Parallel Execution: Selenium Grid allows you to run tests in parallel on multiple browsers and platforms. This can further speed up test execution and increase test coverage.
5. Early Bug Detection: Automated tests can be integrated into the development process, allowing for the early detection and resolution of issues, which can reduce the cost of fixing bugs later in the development lifecycle.
6. Regression Testing: Automation is well-suited for regression testing, ensuring that new code changes do not introduce regressions or break existing functionality.
7. Scalability: As your application grows, you can scale your automated testing efforts to cover new features and functionalities without proportionally increasing the testing team's size.
However, it's essential to consider the costs associated with Selenium automation, including:
1. Initial Development: Writing and maintaining automated test scripts requires an initial investment of time and resources.
2. Maintenance: Test scripts need to be updated and maintained as the application evolves. Changes in the UI or functionality may require corresponding changes in the test scripts.
3. Training: Test automation requires training for team members who may not be familiar with Selenium and automation practices.
4. Infrastructure: Setting up and maintaining the test environment, including hardware, software, and browser configurations, has associated costs.
5. License Costs: While Selenium itself is open source, there may be costs associated with third-party tools or frameworks used in conjunction with Selenium.
To calculate the ROI of Selenium automation, you would typically compare the costs (development, maintenance, training, infrastructure) to the benefits (time savings, improved test coverage, early bug detection) over a specific time period. The goal is to determine whether the efficiency and effectiveness gains from automation justify the initial and ongoing investment.
Question: Selenium Grid Answer : Selenium Grid is a component of the Selenium test automation framework that allows you to perform parallel test execution across multiple machines and browsers. It's particularly useful for speeding up the execution of test suites and for achieving cross-browser and cross-platform testing. Selenium Grid enables you to distribute your test cases and run them concurrently on various nodes (machines), which can significantly reduce the time it takes to execute a large set of tests. Here's an overview of Selenium Grid:

Components of Selenium Grid:
1. Hub: The hub acts as the central point for managing and distributing test execution. When you start a Selenium Grid, you typically start with a hub. The hub receives test requests from the test scripts, forwards those requests to the appropriate nodes, and coordinates the test execution.
It is responsible for maintaining a registry of available nodes and their capabilities (e.g., browsers, versions).
2. Node: Nodes are machines (physical or virtual) that execute test scripts. Nodes register themselves with the hub, indicating their availability and capabilities. These capabilities include the types of browsers and versions installed on the node. Test scripts are executed on nodes, and the results are reported back to the hub.
How Selenium Grid Works:
1. Setting Up the Hub: You start by setting up the hub using a command like `java -jar selenium-server-standalone.jar -role hub`. This starts the hub, and it listens for incoming test requests.
2. Setting Up Nodes: On various machines (which can be different operating systems and browsers), you start nodes using a command like
Program: java -Dwebdriver.chrome.driver="chromedriver.exe" -jar selenium-server-standalone.jar -role node -hub http://hub-address:port/grid/register/`.
Content: This registers the node with the hub, indicating the node's capabilities.
3. Test Script Execution: In your test scripts, you specify the hub's URL. When you run your test scripts, they send requests to the hub, which forwards the requests to available nodes based on the desired browser and platform configurations.
4. Parallel Execution: Selenium Grid can run multiple test scripts concurrently on different nodes. This parallel execution can significantly reduce the time needed for test suites to complete.
5. Test Results: Test results are reported back to the hub, which can be accessed through a web interface. You can see the status and results of each test, including any failures.
Benefits of Selenium Grid:
1. Parallel Test Execution: Selenium Grid enables parallel execution of tests, which reduces test suite execution time.
2. Cross-Browser Testing: You can run tests on different browsers and browser versions in parallel, ensuring cross-browser compatibility.
3. Cross-Platform Testing: Selenium Grid allows you to test on various operating systems, helping to ensure cross-platform compatibility.
4. Scalability: You can easily scale your testing infrastructure by adding more nodes as needed.
5. Resource Optimization: It makes efficient use of available resources by distributing tests across multiple machines.
Question: What is the role of Selenium Grid in parallel testing? Answer: Selenium Grid is a tool used for parallel testing with Selenium WebDriver. It allows for distributing test execution across multiple machines (nodes) to achieve faster test execution and improved efficiency.
Selenium Grid consists of a hub server and multiple node servers, where hub acts as a central point for distributing test execution requests to available nodes.
Nodes are configured with different browser and platform combinations, and tests are executed concurrently on multiple nodes, enabling parallel testing with Selenium WebDriver.
Question: What is PageFactory Answer: PageFactory is a concept used to implement the Page Object Model (POM) design pattern, which helps in creating reusable and maintainable automation scripts for web applications. PageFactory is part of the Selenium WebDriver support library and is primarily used in conjunction with WebDriver to initialize and interact with web elements on a web page.

PageFactory is a class in the Selenium WebDriver support library that provides a way to initialize Page Objects and locate web elements using annotations. It enhances the readability and maintainability of automation code by allowing developers to define page objects in a concise and structured manner.

PageFactory uses annotations provided by Selenium WebDriver, such as @FindBy, @CacheLookup, and @FindBys, to locate and initialize web elements on a web page. These annotations are applied to instance variables representing web elements in a Page Object class.
When a Page Object is initialized using PageFactory, WebDriver automatically initializes the web elements annotated with @FindBy based on the specified locator strategies (e.g., id, name, xpath, cssSelector).
Program: public class LoginPage { private WebDriver driver; @FindBy(id = "username") private WebElement usernameInput; @FindBy(id = "password") private WebElement passwordInput; @FindBy(xpath = "//button[@type='submit']") private WebElement loginButton; // Constructor public LoginPage(WebDriver driver) { this.driver = driver; // Initialize elements using PageFactory PageFactory.initElements(driver, this); } // Methods to interact with web elements public void enterUsername(String username) { usernameInput.sendKeys(username); } public void enterPassword(String password) { passwordInput.sendKeys(password); } public void clickLoginButton() { loginButton.click(); } } Question: Explain the concept of WebDriverEventListener in Selenium WebDriver. Answer: WebDriverEventListener is an interface in Selenium WebDriver that allows users to listen to events triggered by WebDriver actions (e.g., element click, page navigation) and perform custom actions or logging.
It provides methods like beforeClickOn, afterClickOn, beforeNavigateTo, afterNavigateTo, etc., which can be implemented to customize WebDriver behavior.
Question: Explain the concept of headless browser testing in Selenium WebDriver. Answer: Headless browser testing is a technique used for running automated tests without the graphical user interface (GUI) of the browser.

Headless browsers like PhantomJS, Headless Chrome, and Headless Firefox allow tests to be executed in a headless environment, improving test performance and resource utilization.

Headless browser testing is useful for running tests in headless Continuous Integration (CI) environments, executing tests on servers without a graphical display, and running tests in parallel on virtual machines.

Question: How to create Jenkins job

Answer:

  • Create New item
      Maven Project
  • General Tab
    • Maven Project Name
    • Description
    • Source code Management
      • None
      • GIT
        • Repository URL
        • Credentails
        • Branches
          • e.g.- */master
    • Build Triggers
    • Build Environment
    • Pre Steps
    • Build
      • Root POM
        • pom.xml
      • Goals and options
        • clean install
    • Post steps
      • publish TestNG results
        • TestNG XML report pattern
          • */testng-result.xml
      • publish HTML reports
        • Report
          • Add

Tuesday, 22 August 2023

Selenium MC interview questions

Question :Selenium tests _____________.

DOS applications

Browser-based applications

GUI applications

None of the above

Correct Answer : Browser-based applications


Question :What does the term DOM refers to ?

Dynamic Object Model

Document Object Model

Data Object Model

Document Flow Object Model

Correct Answer : Document Object Model


Question :What is a test suite made of ?

Test packs

Tests

Test blocks

Test pattern

Correct Answer : Tests


Question :Select the Browser which is supported by Selenium IDE

Google chrome

Opera mini

Mozilla Firefox

Internet Explorer

Correct Answer :  Mozilla Firefox


Question :Select the operating system which is NOT supported by Selenium IDE.

Unix

Linux

Windows

Solaris

Correct Answer :  Unix


Question :The Web driver is used

To execute tests on the HtmlUnit browser.

To design a test using Selenese

To quickly create tests

To test a web application against Firefox only.

Correct Answer :  To execute tests on the HtmlUnit browser.


Question :The Selenium IDE is used

To create customized test results.

To deploy your tests across multiple environments using Selenium Grid

To test with HTMLUnit

To test a web application against Firefox only.

Correct Answer :  To test a web application against Firefox only.


Question :Select the method which selects the option at the given index.

selectByIndex()

selectIndex()

selectedByIndex()

selectByIndexes()

Correct Answer :  selectByIndex()


Question :The Selenium

Provides professional customer support

Test Reports are generated automatically

Comes with a built-in object repository

Cannot access elements outside of the web application under test

Correct Answer :  Cannot access elements outside of the web application under test


Question :Which command can be used to enter values onto text boxes?

sendsKeys()

sendKey()

sendKeys

sendKeys()

Correct Answer :  sendKeys()


Question :The Actions commands

are commands that directly interact with page elements.

are commands that allow you to store values to a variable.

are commands that verify if a certain condition is met.

All the above

Correct Answer : are commands that directly interact with page elements.


Question :Select the command which is used to pause execution until the page is loaded completely.

waitForPageToLoad

waitForElementPresent

waitForPage

waitForLoad

waitForPageToLoad


Question :Select the syntax to locate an element using inner text.

css=tag:contains(“inner text”)

css=tag:value(“inner text”)

css=tag:attributes(“inner text”)

css=tag:class(“inner text”)

Correct Answer : css=tag:contains(“inner text”)


Question :What is TestNG?

TestNextGeneration

TestNewGenerlization

TestNewGeneration

TestNextGenerations

Correct Answer : TestNextGeneration


Question :Select the variation which finds elements based on the driver’s underlying CSS selector engine in Web driver Selenium.

By.cssSelected

By.cssSelection

By.cssSelector

By.Selectcs

Correct Answer : By.cssSelector


Question :Select the variation which locates elements by the value of the “name” attribute in Web driver Selenium

By.name

By.nametag

By.tagname

By.nametags

Correct Answer : By.name


Question :Select the variation which locates elements by the value of their “id” attribute in Web Driver Selenium

By.id

By.idno

By.id_no

By.tag_id

Correct Answer : By.id


Question :Select the Get command which fetches the inner text of the element that you specify in Web driver Selenium.

getinnerText()

get_in_Text()

get_inner_Text()

getText()

Correct Answer : getText()


Question :Which Navigate command takes you forward by one page on the browser’s history in Web driver Selenium.

navigate.forward()

navigate().forward()

navigate()_forward()

navigate_forword()

Correct Answer : navigate().forward()


Question :Select the method which clears all selected entries in Web driver Selenium.

dselectAll()

deselect_All()

dselect_All()

deselectAll()

Correct Answer : deselectAll()


Question :Method which selects the option which displays the text matching the parameter passed to it

selectVisibleText()

selectByVisibleText()

select_VisibleText()

select_ByVisibleText()

Correct Answer : selectByVisibleText()


Question :Select the method which performs a context-click at the current mouse location.

click_Context()

context.Click()

contextClick()

context_Click()

Correct Answer : contextClick()


Question :Which command should be used to confirm that test will pass in the future, when new element is added after page loaded?

waitForElementPresent

pause

assertElementPresent

None of these

Correct Answer : waitForElementPresent


Question :Which command is used to extend the time limit of WAITFOR command?

Extend waitFor (time in sec)

waitFor (time in sec) extend

setTimeout (time in sec)

setTimeout.

Correct Answer : setTimeout.


Question :___________ finds the item ending with the value passed in. This is the equivalent to the XPath ends-with. Is concern with?

^=

$=

*=

&=

Correct Answer : $=


Question :In Selenium, Following Axis is related to:

Selects all the siblings after the current element

Selects all elements that follow the closing tab of the current elements.

Selects all of the siblings before the current element

Selects all elements that are before the current element

Selects all elements that follow the closing tab of the current elements.


Question :In regular Expression * quantifier refers to:

0 or more of the preceding character.

1 or more of the preceding character

0 or 1 of the preceding character

All of these

0 or more of the preceding character.


Question :Which regular expression sequence that loosely translates to “anything or nothing?”

.* (dot star)

*. (star dot)

“?

*+The // tells the query that

.* (dot star)


Question :If you wanted to access the element that has the text “This element has an ID that changes every time the page is loaded” in it, then which of the following is used:

//div[contains(@id,’time_’)]

//div[contains(@id_time())]

//div[parameter(@id_time())]

//div[parameter(@id,’time_’)]

Correct Answer : //div[contains(@id,’time_’)]


Question :To delete a cookie we need to call the deleteCookie method, passing in two parameters.

The first parameter is the name of the cookie, and the second parameter is where it was created.

The first parameter is where it was created, and the second parameter is the name of cookie.

None of these

A and B

Correct Answer : The first parameter is the name of the cookie, and the second parameter is where it was created.


Question :What is the default port number used by hub in selenium?

4444

2222

1111

3333

Correct Answer : 4444


Question :Which two commands you use to validate a button?

VerifyTextPresent and assertTextPresent

VerifyElementPresent and assertElementPresent

VerifyAlertPresent and assertAlertPresent

VerifyAlert and assertAlert

Correct Answer : VerifyElementPresent and assertElementPresent


Question :Selects all the parent, grandparent, and so on of the element is related to which axis name in Selenium:

Ancestor

Preceding

Parent

All of these.

Correct Answer : Ancestor


Question :Which command is used to open a web page in Selenium WebDriver?

open()

start()

get()

load()

get()


Question :How can you find an element by its ID using Selenium WebDriver?

findElement(By.id('elementId'))

getElementById('elementId')

findElementById('elementId')

getElement(By.id('elementId'))

findElement(By.id('elementId'))


clear the contents of an input field using Question :Which method is used to submit a form using Selenium WebDriver?

submitForm()

sendForm()

submit()

clickForm()

Correct Answer : submit()


Question :How do you switch to a new window or tab using Selenium WebDriver?

switchToWindow()

switchToTab()

switchToNewWindow()

switchTo().window(handle)

Correct Answer : switchTo().window(handle)


Question :How do you handle alerts in Selenium WebDriver?

handleAlert()

acceptAlert()

switchToAlert()

dismissAlert()

Correct Answer : switchToAlert()


Question :How do you perform mouse hover action using Selenium WebDriver?

hover()

mouseHover()

moveToElement()

moveMouseTo()

Correct Answer : moveToElement()


Question :How do you get the current URL of the web page using Selenium WebDriver?

getCurrentURL()

getURL()

fetchURL()

retrieveURL()

Correct Answer : getCurrentURL()


Question :Which method is used to maximize the browser window using Selenium WebDriver?

maximizeWindow()

maximize()

fullscreen()

setMaximized()

Correct Answer : maximize()


Question :How do you perform the double-click action using Selenium WebDriver?

doubleClick()

clickTwice()

performDoubleClick()

doubleTap()

Correct Answer : doubleClick()


Question :What is the command to refresh the web page using Selenium WebDriver?

refresh()

reload()

update()

navigate().refresh()

Correct Answer : navigate().refresh()


Question :How do you handle frames using Selenium WebDriver?

switchToFrame()

switchFrame()

frameTo()

switchTo().frame()

Correct Answer : switchTo().frame()


Question :Which method is used to get the text of an element using Selenium WebDriver?

text()

getValue()

getText()

innerText()

Correct Answer : getText()


Question :What is the command to close the current window using Selenium WebDriver?

close()

quit()

exit()

end()

Correct Answer : close()


Question :How do you handle multiple windows or tabs using Selenium WebDriver?

getWindowHandles()

getWindowIds()

getWindowNames()

getAllWindowHandles()

Correct Answer : getWindowHandles()


Question :Which method is used to execute JavaScript code using Selenium WebDriver?

executeJS()

runScript()

executeScript()

executeJavaScript()

Correct Answer : executeScript()


Question :How do you scroll down to the bottom of the web page using Selenium WebDriver?

scrollDown()

scrollToBottom()

scrollToEnd()

scrollBy(0, document.body.scrollHeight)

Correct Answer : scrollBy(0, document.body.scrollHeight)


Question :How do you handle keyboard events using Selenium WebDriver?

handleKeyboard()

sendKeys()

typeKeys()

keyboardEvent()

Correct Answer : sendKeys()


Question :Which method is used to drag and drop elements using Selenium WebDriver?

dragAndDrop()

dragDrop()

performDragAndDrop()

dragTo()

Correct Answer : dragAndDrop()


Question :What is the correct way to switch to the default content from a frame using Selenium WebDriver?

switchToDefaultContent()

switchToDefault()

switchToMainFrame()

switchTo().defaultContent()

Correct Answer : switchTo().defaultContent()


Question :Which method is used to get the CSS value of an element using Selenium WebDriver?

getCssValue()

fetchCssValue()

getStyle()

cssProperty()

Correct Answer : getCssValue()


Question :What is the command to navigate to a URL using Selenium WebDriver?

navigateTo()

goTo()

loadURL()

get()

get()


Question :How do you perform right-click context menu action using Selenium WebDriver?

rightClick()

contextClick()

performContextClick()

rightTap()

contextClick()


Question :What is the command to get the title of the web page using Selenium WebDriver?

getTitle()

fetchTitle()

getPageTitle()

getWindowTitle()

getTitle()


Question :Which method is used to select an option from a dropdown using Selenium WebDriver?

selectDropdownOptionByText(element, 'option_text')

selectDropdownOptionByIndex(element, index)

element.selectByVisibleText('option_text')

element.selectByValue('option_value')

element.selectByVisibleText('option_text') 

 

Question :How do you handle multiple windows or tabs in Selenium WebDriver?

driver.switchToNewWindow()

driver.switchToWindow(index)

driver.switchToNextWindow()

driver.switchToWindow(handle)

driver.switchToWindow(handle) 

 

Question :What is the correct way to wait for an element to be visible using Selenium WebDriver?

driver.waitForElementVisible(element)

driver.waitUntilElementVisible(element)

wait.until(ExpectedConditions.visibilityOf(element))

wait.until(elementToBeVisible(element))

wait.until(ExpectedConditions.visibilityOf(element)) 

 

Question :How do you handle browser cookies using Selenium WebDriver?

driver.setCookie(cookie)

driver.addCookie(cookie)

driver.updateCookie(cookie)

driver.deleteCookie(cookie)

driver.addCookie(cookie) 

 

Question :What is the correct way to handle basic authentication pop-ups in Selenium WebDriver?

driver.handleAuthentication(username, password)

driver.authenticate(username, password)

driver.switchTo().alert().authenticateUsing(new UserAndPassword(username, password))

driver.switchTo().alert().setCredentials(username, password)

driver.switchTo().alert().authenticateUsing(new UserAndPassword(username, password)) 

 

Question :How do you handle mouse hover actions in Selenium WebDriver?

driver.hoverOverElement(element)

driver.moveToElement(element)

actions.moveToElement(element).perform()

actions.hover(element).perform()

Correct Answer :  actions.moveToElement(element).perform() 

 

Question :What is the correct way to execute JavaScript code using Selenium WebDriver?

driver.executeScript('javascript_code')

driver.runScript('javascript_code')

driver.executeJavaScript('javascript_code')

driver.runJavaScript('javascript_code')

Correct Answer :  driver.executeScript('javascript_code') 

 

Question : How do you handle keyboard key presses in Selenium WebDriver?

actions.keyDown(Keys.ENTER).perform()

actions.sendKeys(Keys.ENTER).release().perform()

actions.sendKeys(Keys.ENTER).perform()

actions.keyDown(Keys.ENTER).release().perform()

Correct Answer :  actions.sendKeys(Keys.ENTER).perform() 

 

Question : What is the correct way to simulate browser navigation using Selenium WebDriver?

driver.navigate().to('url')

driver.navigate().back()

driver.navigate().refresh()

driver.navigate().forward()

Correct Answer :  driver.navigate().to('url') 

 

Question : How do you handle frames and iframes in Selenium WebDriver?

driver.switchToFrame(frame)

driver.switchTo().frame(frame)

driver.switchTo().frame(index)

driver.switchToFrame(index)

Correct Answer :  driver.switchTo().frame(frame) 

 

Question : What is the correct way to take a screenshot using Selenium WebDriver?

driver.takeScreenshot('file_path')

driver.getScreenshotAs('file_path')

driver.saveScreenshot('file_path')

driver.captureScreenshot('file_path')

Correct Answer :  driver.getScreenshotAs('file_path') 

 

Question : How do you handle SSL certificate errors in Selenium WebDriver?

driver.acceptSSLCertificate()

driver.handleSSLCertificateError('proceed')

driver.handleSSLCertificateError('cancel')

driver.ignoreSSLCertificateError()

Correct Answer :  driver.acceptSSLCertificate() 

 

Question : What is the correct way to simulate mouse double-click using Selenium WebDriver?

actions.doubleClick(element).perform()

actions.mouseDoubleClick(element).perform()

actions.doubleClickAndHold(element).perform()

actions.doubleClickAndHold(element).release().perform()

Correct Answer :  actions.doubleClick(element).perform() 

 

Question : What is the correct way to check if an element is present and visible using Selenium WebDriver?

driver.isElementDisplayed(element)

driver.isElementPresent(element)

driver.isElementVisible(element)

element.isDisplayed()

Correct Answer :  element.isDisplayed() 

 

Question : How do you handle drag and drop actions in Selenium WebDriver?

actions.dragAndDrop(source, target).perform()

actions.clickAndHold(source).moveToElement(target).release().perform()

actions.dragAndDropByOffset(source, x, y).perform()

actions.clickAndHold(source).moveByOffset(x, y).release().perform()

Correct Answer :  actions.dragAndDrop(source, target).perform() 

 

Question : Which type of framework promotes the use of data-driven testing in Selenium?

Keyword-driven framework

Hybrid framework

Data-driven framework

Page Object Model

Correct Answer : Data-driven framework


Question : What is the primary purpose of the Page Object Model (POM) in Selenium?

Managing browser sessions

Creating modular and reusable code

Handling multiple windows

Generating test reports

Correct Answer : Creating modular and reusable code


Question : In the TestNG framework, which annotation is used to mark a method as a test case?

@BeforeMethod

@Test

@AfterClass

@DataProvider

Correct Answer : @Test


Question : Which framework facilitates the parallel execution of test cases in Selenium?

JUnit

TestNG

NUnit

Cucumber

Correct Answer : TestNG


Question : What is the purpose of the "assert" statements in testing frameworks like TestNG or JUnit?

Pause test execution

Generate logs

Verify expected outcomes

Manage browser instances

Correct Answer : Verify expected outcomes


Question : Which type of framework combines the features of both data-driven and keyword-driven frameworks?

Modular framework

Page Object Model (POM)

Hybrid framework

Behavior-Driven Development (BDframework

Correct Answer : Hybrid framework


Question : What is the purpose of a testNG.xml file in TestNG framework?

Define test scenarios

Store test data

Configure test execution settings

Manage page objects

Correct Answer : Configure test execution settings


Question : In Selenium, which design pattern is commonly used to create an instance of a browser driver?

Singleton pattern

Observer pattern

Factory pattern

Builder pattern

Correct Answer : Factory pattern


Question : Which framework facilitates behavior-driven testing in Selenium projects?

JUnit

TestNG

Cucumber

NUnit

Correct Answer : Cucumber


Question : What is the purpose of the "dataProvider" annotation in TestNG?

Manage test data

Perform assertions

Define test scenarios

Handle browser sessions

Correct Answer : Manage test data


Question : Which design pattern is associated with the concept of encapsulating an object's behavior in Selenium?

Singleton pattern

Page Object Model (POM)

Observer pattern

Composite pattern

Correct Answer : Page Object Model (POM)


Question : Which framework allows the execution of test scripts across different browsers and platforms in Selenium Grid?

TestNG

JUnit

Selenium WebDriver

TestNG with parallel execution

Correct Answer : Selenium WebDriver


Question : What is the primary purpose of the "tearDown" method in testing frameworks like JUnit or TestNG?

Set up test data

Close browser sessions

Perform assertions

Define test scenarios

Correct Answer : Close browser sessions


Question : Which annotation is used to mark a method that runs before every test case in TestNG?

@BeforeSuite

@BeforeTest

@BeforeMethod

@BeforeClass

Correct Answer : @BeforeMethod


Question : In the context of Selenium, what does the term "WebDriverEventListener" refer to?

A design pattern for managing browser sessions

A component for handling AJAX calls

An interface for capturing events during test execution

A utility for managing cookies

Correct Answer : An interface for capturing events during test execution


Question : Which design pattern in Selenium promotes the creation of flexible and maintainable test scripts by separating concerns?

Singleton pattern

Observer pattern

Page Object Model (POM)

Factory pattern

Correct Answer : Page Object Model (POM)


Question : Which method is used to take screenshots in Selenium WebDriver?

captureScreenshot()

takeScreenshot()

captureScreen()

getScreenshot()

Correct Answer : takeScreenshot()


Question : In a Selenium project, which framework is commonly used for managing and organizing test data?

JUnit

TestNG

Apache POI

Selenium Grid

Correct Answer : Apache POI


Question : Which design pattern is commonly used to implement the concept of parallel test execution in Selenium Grid?

Observer pattern

Singleton pattern

Factory pattern

Decorator pattern

Correct Answer : Factory pattern


Question : What is the purpose of the "@FindBy" annotation in the Page Object Model (POM)?

Identifying test methods

Locating web elements

Defining test data

Handling test dependencies

Correct Answer : Locating web elements


Question : Which Selenium WebDriver method is used to switch to a different frame within a web page?

switchToFrame()

switchToWindow()

switchToAlert()

switchTo().frame()

Correct Answer : switchTo().frame()


Question : What is the primary purpose of the "SoftAssertions" library in testing frameworks like TestNG?

Handling exceptions

Generating test reports

Performing assertions without stopping the test execution on failure

Managing browser sessions

Correct Answer : Performing assertions without stopping the test execution on failure


Question : In Selenium, which type of locator is used to find web elements by their link text?

CSS selector

XPath

ID

LinkText

Correct Answer : LinkText


Question : Which testing framework is commonly associated with the concept of "test suites" in Selenium projects?

JUnit

TestNG

NUnit

Cucumber

Correct Answer : TestNG


Question : What is the primary purpose of the "WebDriverWait" class in Selenium?

Managing browser sessions

Executing JavaScript code

Explicitly waiting for a certain condition before proceeding with the test

Switching between windows

Correct Answer : Explicitly waiting for a certain condition before proceeding with the test


Question : Which method is used to perform mouse hover actions in Selenium WebDriver?

hover()

moveToElement()

mouseOver()

performHover()

Correct Answer : moveToElement()


Question : What is the purpose of the "TestBase" class in a Selenium project?

Managing test data

Executing test cases

Serving as a base class for common functionalities shared across test classes

Handling browser sessions

Correct Answer : Serving as a base class for common functionalities shared across test classes


Question : Which annotation is used to mark a method that runs after every test case in TestNG?

@AfterSuite

@AfterTest

@AfterMethod

@AfterClass

Correct Answer : @AfterMethod


Question : In Selenium, what is the purpose of the "Actions" class?

Managing browser sessions

Performing advanced user interactions like drag-and-drop

Executing JavaScript code

Switching between frames

Correct Answer : Performing advanced user interactions like drag-and-drop


Question : Which method is used to select an option from a dropdown menu in Selenium WebDriver?

click()

selectByIndex()

setValue()

chooseOption()

Correct Answer : selectByIndex()


Question : Which design pattern is commonly used for creating dynamic and flexible object repositories in Selenium projects?

Factory pattern

Singleton pattern

Prototype pattern

Decorator pattern

Correct Answer : Factory pattern


Question : What is the purpose of the "@BeforeSuite" annotation in TestNG?

Set up test data

Execute test cases

Perform actions before the entire test suite

Configure test execution settings

Correct Answer : Perform actions before the entire test suite


Question : In Selenium WebDriver, which method is used to simulate keyboard actions such as pressing keys?

type()

sendKeys()

setText()

enterKey()

Correct Answer : sendKeys()


Question : What is the purpose of the "extentReports" library in Selenium projects?

Managing test data

Generating test reports

Performing assertions

Handling browser sessions

Correct Answer : Generating test reports


Question : Which Selenium WebDriver method is used to navigate backward in the browser history?

navigateToBack()

goBack()

back()

previousPage()

Correct Answer : back()


Question : What is the purpose of the "Apache POI" library in Selenium projects?

Performing database operations

Managing test data

Generating test reports

Handling Excel files

Correct Answer : Handling Excel files


Question : Which annotation is used to mark a method that runs before the entire test suite in TestNG?

@BeforeSuite

@BeforeTest

@BeforeClass

@BeforeMethod

Correct Answer : @BeforeSuite


Question : Which class in Selenium is used to set browser-specific settings for Chrome?

ChromeSettings

ChromeDriver

ChromeOptions

ChromeBrowserSettings

ChromeOptions


Question : Which of the following methods is used to add an argument to ChromeOptions?

addPreference()

addArguments()

setCapability()

addExtensions()

addArguments()


Question : Which capability in DesiredCapabilities is used to run Chrome in headless mode?

headless

disable-gpu

chromeOptions.headless

chrome.switches

headless


Question : How can you set a custom download directory in Chrome using ChromeOptions?

options.addPreference("download.default_directory", path);

options.setDownloadDirectory(path);

options.addArguments("download.default_directory", path);

options.setExperimentalOption("prefs", prefs);

options.setExperimentalOption("prefs", prefs);


Question : Which method is used to merge ChromeOptions with DesiredCapabilities in Selenium WebDriver?

options.merge(capabilities);

capabilities.setOptions(options);

options.addCapabilities(capabilities);

capabilities.merge(options);

options.merge(capabilities);


Question : What is the purpose of using setCapability() method in DesiredCapabilities?

To set system properties.

To define test data.

To set browser-specific capabilities.

To configure WebDriver timeouts.

To set browser-specific capabilities.


Question : Which of the following is the correct way to disable the "Save Password" prompt in Chrome using ChromeOptions?

options.addArguments("disable-password-manager");

options.setCapability("disable-password-saving", true);

options.setExperimentalOption("prefs", {"credentials_enable_service": false});

options.setPreference("disablePasswordManager", true);

options.setExperimentalOption("prefs", {"credentials_enable_service": false});


Question : Which ChromeOptions argument is used to start Chrome maximized?

--start-maximized

--maximize

--start-fullscreen

--window-size=1920,1080

--start-maximized


Question : How do you add an extension to Chrome using ChromeOptions?

options.setExperimentalOption("extensions", extensionPath);

options.addExtensions(new File(extensionPath));

options.addArguments("--load-extension=" + extensionPath);

options.setCapability("chrome.loadExtension", extensionPath);

options.addExtensions(new File(extensionPath));


Question : Which of the following is a valid DesiredCapabilities property for enabling logging in Chrome?

capabilities.setCapability("loggingPrefs", "ALL");

capabilities.setCapability("goog:loggingPrefs", "ALL");

capabilities.setCapability("chromeOptions.loggingPrefs", "ALL");

capabilities.setCapability("browserLogging", "ALL");

capabilities.setCapability("goog:loggingPrefs", "ALL");


Question :Which statement is TRUE about findElement()?

Returns null if element not found

Returns empty list if element not found

Throws NoSuchElementException if element not found

Throws ElementNotVisibleException

Correct Answer : Throws NoSuchElementException if element not found


Question :Which return type is correct for findElements()?

WebElement

Set

ArrayList

List

Correct Answer : List


Question :Which method belongs to JavascriptExecutor?

executeAsync()

executeJavaScript()

executeScript()

runScript()

Correct Answer : executeScript()


Question :Which is the CORRECT casting?

JavascriptExecutor js = new JavascriptExecutor();

JavascriptExecutor js = (JavascriptExecutor) driver;

WebDriver js = (JavascriptExecutor) driver;

JavascriptExecutor js = driver.executeScript();

Correct Answer : JavascriptExecutor js = (JavascriptExecutor) driver;


Question :Which locator supports both starts-with() and contains()?

CSS Selector

ID

Name

XPath

Correct Answer : XPath


Question :Which wait ignores polling interval configuration?

Implicit Wait

Explicit Wait

Fluent Wait

Thread.sleep()

Correct Answer : Thread.sleep()


Question :What happens if Implicit Wait is set to 10 seconds and Explicit Wait to 20 seconds?

Explicit overrides Implicit

Implicit overrides Explicit

They add up to 30 seconds

Unpredictable wait behavior

Correct Answer : Unpredictable wait behavior


Question :Which method is NOT present in WebDriver.Navigation?

back()

forward()

refresh()

navigate()

Correct Answer : navigate()


Question :Which interface is implemented by RemoteWebDriver?

TakesScreenshot

JavascriptExecutor

WebDriver

All of the above

Correct Answer : All of the above


Question :Which is the correct way to take screenshot?

driver.captureScreenshot()

((TakesScreenshot)driver).takeScreenshot()

((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)

driver.getScreenshot()

Correct Answer : ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)


Question :Which exception occurs when DOM is refreshed?

NoSuchElementException

TimeoutException

StaleElementReferenceException

ElementNotVisibleException

Correct Answer : StaleElementReferenceException


Question :Which method belongs to Select class?

selectVisibleText()

selectByText()

selectByVisibleText()

selectText()

Correct Answer : selectByVisibleText()


Question :Which statement about isDisplayed() is TRUE?

Throws exception if element hidden

Returns null if element hidden

Returns false if element hidden

Returns true if element exists in DOM

Correct Answer : Returns false if element hidden


Question :What is the return type of getCssValue()?

int

boolean

String

Object

Correct Answer : String


Question :Which method switches control to default page from iframe?

switchTo().parent()

switchTo().main()

switchTo().defaultContent()

switchTo().home()

Correct Answer : switchTo().defaultContent()


Question :Which statement about Selenium Grid is TRUE?

Node distributes test cases

Hub executes test cases

Hub controls nodes and distributes tests

Grid only supports Chrome

Correct Answer : Hub controls nodes and distributes tests


Question :Which command is INVALID in Selenium IDE?

open

type

click

getTitle

Correct Answer : getTitle


Question :Which method returns current URL?

getUrl()

getCurrentUrl()

currentUrl()

getURL()

Correct Answer : getCurrentUrl()


Question :Which command fails at compile time?

driver.switchTo().alert().accept();

driver.switchTo().frame(0);

driver.switchTo().window();

driver.navigate().refresh();

Correct Answer : driver.switchTo().window();


Question :What is the return type of driver.switchTo()?

WebDriver

Set of Elements

Options

TargetLocator

Correct Answer : TargetLocator


Question :Which statement causes a compile-time error?

driver.switchTo().alert().accept();

driver.switchTo().frame("frame1");

driver.switchTo().window();

driver.switchTo().defaultContent();

Correct Answer : driver.switchTo().window();


Question :Which class directly implements WebDriver?

ChromeDriver

ChildWebDriver

MyDriver

RemoteWebDriver

Correct Answer : RemoteWebDriver


Question :Which interface allows JavaScript execution?

WebDriver

RemoteWebDriver

JavascriptExecutor

ExecuteScript

Correct Answer : JavascriptExecutor


Question :Which cast is mandatory to execute JavaScript?

(WebDriver) driver

(RemoteWebDriver) driver

(JavascriptExecutor) driver

No casting required

Correct Answer : (JavascriptExecutor) driver


Question :What happens if findElements() finds nothing?

Throws NoSuchElementException

Returns null

Returns empty List

Stops execution

Correct Answer : Returns empty List


Question :Which is TRUE about isDisplayed()?

Checks presence in DOM

Throws exception if hidden

Returns false if hidden

Returns null if not visible

Correct Answer : Returns false if hidden


Question :Which statement about Implicit Wait is TRUE?

Applied per element

Applies only to findElement()

Applied globally for session

Overrides Explicit Wait

Correct Answer : Applied globally for session


Question :What does driver.findElements(By.id("x")).size(); return if nothing found?

Exception

null

0

-1

Correct Answer : 0


Question :Which method belongs to Options interface?

navigate()

switchTo()

manage()

addCookie()

Correct Answer : addCookie()


Question :Which Selenium exception is unchecked?

IOException

SQLException

NoSuchElementException

InterruptedException

Correct Answer : NoSuchElementException


Question :Which WebDriver command closes only the current window?

quit()

close()

end()

stop()

Correct Answer : close()


Question :Which is the correct screenshot syntax?

driver.getScreenshot()

((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)

driver.capture()

Screenshot.take()

Correct Answer : ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)


Question :Which XPath is syntactically INVALID?

//input[@id='x']

//*[@class='a']

//input[@id='x' and]

//div[contains(@id,'a')]

Correct Answer : //input[@id='x' and]


Question :Which Selenium component supports parallel execution across machines?

IDE

WebDriver

Grid

RemoteControl

Correct Answer : Grid


Question :Which returns a Set?

getWindowHandle()

getWindowHandles()

getWindows()

getAllHandles()

Correct Answer : getWindowHandles()


Question :Which call fails at runtime but compiles fine?

driver.switchTo().frame(0);

driver.findElement(By.id("notPresent"))

driver.getTitle();

driver.navigate().back();

Correct Answer : driver.findElement(By.id("notPresent"))


Question :Which statement is TRUE about Selenium IDE?

Supports Java coding

Can handle dynamic waits

Supports record & playback only

Supports Grid execution

Correct Answer : Supports record & playback only


Question :Return type of driver.switchTo()?

WebDriver

Options

TargetLocator

Navigation

Correct Answer : TargetLocator


Question :Which call causes compile-time error?

driver.switchTo().alert().accept();

driver.switchTo().frame(0);

driver.switchTo().window();

driver.switchTo().defaultContent();

Correct Answer : driver.switchTo().window();


Question :Mandatory cast for JavaScript execution?

WebDriver

RemoteWebDriver

JavascriptExecutor

ExecuteScript

Correct Answer : JavascriptExecutor


Question :Which locator is fastest?

XPath

CSS Selector

Name

ID

Correct Answer : ID


Question :What does findElements() return if nothing found?

null

Exception

Empty List

FALSE

Correct Answer : Empty List


Question :Which wait is global?

Explicit

Fluent

Implicit

Thread.sleep()

Correct Answer : Implicit


Question :Which method belongs to Select?

selectByText()

selectByVisibleText()

selectText()

selectVisible()

Correct Answer : selectByVisibleText()


Question :Which exception when DOM refreshes?

NoSuchElementException

TimeoutException

StaleElementReferenceException

ElementNotVisibleException

Correct Answer : StaleElementReferenceException


Question :Which is NOT a WebDriver method?

getTitle()

getCurrentUrl()

open()

close()

Correct Answer : open()


Question :Return type of getWindowHandles()?

String

List

Set

Map<String,String>

Correct Answer : Set


Question :Which statement about Thread.sleep() is TRUE?

Dynamic wait

Conditional wait

Static wait

Polling wait

Correct Answer : Static wait


Question :Which belongs to Options?

navigate()

switchTo()

manage()

addCookie()

Correct Answer : addCookie()


Question :Correct screenshot syntax?

driver.capture()

driver.getScreenshot()

((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)

Screenshot.take()

Correct Answer : ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)


Question :Which is INVALID XPath?

//input[@id='x']

//*[@class='a']

//input[@id='x' and]

//div[contains(@id,'a')]

Correct Answer : //input[@id='x' and]


Question :Which Selenium component supports parallel execution?

IDE

RC

Grid

WebDriver

Correct Answer : Grid


Question :Which method returns page title?

getPageTitle()

title()

getTitle()

pageTitle()

Correct Answer : getTitle()


Question :Which command closes all browser windows?

close()

quit()

end()

stop()

Correct Answer : quit()


Question :Which is NOT Selenium exception?

TimeoutException

NoSuchFrameException

StaleElementReferenceException

ElementNotFoundException

Correct Answer : ElementNotFoundException


Question :Which command is NOT valid in Selenium IDE?

click

type

open

navigate

Correct Answer : navigate


Question :Return type of getCssValue()?

int

boolean

String

Object

Correct Answer : String


Question :Which locator supports contains()?

CSS

ID

Name

XPath

Correct Answer : XPath


Question :Which method switches to main page from iframe?

parentFrame()

switchMain()

defaultContent()

home()

Correct Answer : defaultContent()


Question :Which interface enables screenshots?

WebDriver

TakesScreenshot

Screenshot

Capture

Correct Answer : TakesScreenshot


Question :Which is TRUE about Implicit + Explicit waits together?

They add up

Explicit overrides

Implicit overrides

Unpredictable behavior

Correct Answer : Unpredictable behavior


Question :Which class is used for mouse actions?

Robot

EventFiringWebDriver

Actions

Mouse

Correct Answer : Actions


Question :Which method is NOT in Actions?

doubleClick()

contextClick()

dragAndDrop()

mouseHover()

Correct Answer : mouseHover()


Question :Which returns current URL?

getUrl()

getCurrentUrl()

currentUrl()

getURL()

Correct Answer : getCurrentUrl()


Question :Which wait supports polling interval?

Implicit

Explicit

Fluent

Thread.sleep()

Correct Answer : Fluent


Question :Which Selenium 4 feature is NEW?

Grid

IDE

Relative Locators

XPath

Correct Answer : Relative Locators


Question :Which method belongs to Navigation?

get()

back()

open()

switchTo()

Correct Answer : back()


Question :Which returns WebElement?

findElements()

findElement()

getElements()

locate()

Correct Answer : findElement()


Question :Which is fastest locator?

XPath

Name

CSS

ID

Correct Answer : ID


Question :Which exception when alert not present?

NoSuchElementException

NoAlertPresentException

TimeoutException

AlertNotFoundException

Correct Answer : NoAlertPresentException


Question :Which is NOT Selenium component?

IDE

WebDriver

Grid

JUnit

Correct Answer : JUnit


Question :Which IDE command has two parameters?

open

click

type

assertTitle

Correct Answer : type


Question :Which method checks visibility?

isEnabled()

isSelected()

isDisplayed()

isPresent()

Correct Answer : isDisplayed()


Question :Which call compiles but fails at runtime?

driver.getTitle()

driver.navigate().back()

driver.findElement(By.id("x"))

driver.getCurrentUrl()

Correct Answer : driver.findElement(By.id("x"))


Question :Which locator is dynamic-friendly?

ID

Name

XPath

LinkText

Correct Answer : XPath


Question :Which Grid component executes tests?

Hub

Node

Client

Server

Correct Answer : Node


Question :Which Selenium version removed RC?

Selenium 2

Selenium 3

Selenium 4

Selenium 1

Correct Answer : Selenium 3


Question :Which method clears input field?

delete()

remove()

clear()

reset()

Correct Answer : clear()


Question :Which is NOT valid CSS selector?

#id

.class

tagname

//input[@id='x']

Correct Answer : //input[@id='x']


Question :Which method submits form?

send()

clickSubmit()

submit()

post()

Correct Answer : submit()


Question :Which exception is unchecked?

IOException

SQLException

NoSuchElementException

InterruptedException

Correct Answer : NoSuchElementException


Question :Which method sets browser size?

resize()

setSize()

manage().window().setSize()

windowSize()

Correct Answer : manage().window().setSize()


Question :Which returns dimension?

getLocation()

getSize()

getRect()

getDimension()

Correct Answer : getSize()


Question :Which command maximizes browser?

fullscreen()

manage().window().maximize()

maximize()

setMax()

Correct Answer : manage().window().maximize()



Featured

Software Testing

Question: What is software testing, and why is it important?  Answer: Software testing is the process of evaluating a software application ...

popular