Interview Questions for API Testing 2025

HOME

https://www.qaautomation.expert
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
  {
     "username": "exampleuser",
     "password": "examplepassword"
   }
   

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
 x-api-key: YOUR_API_KEY

'or 1=1--
"and 1=1--
echo "malicious" >> /var/www/html/index.html
rm file.txt; cat /etc/passwd

https://api.example.com/items?page=2&limit=50
https://api.example.com/products?category=electronics&price<1000

name: API Tests

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '14'

    - name: Install Newman
      run: npm install -g newman

    - name: Run API tests with Newman
      run: newman run test.json

{
  "token": "eyJhbGciOiJIUzI1NiIsInR..."
}

import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class APITests {

        String BaseURL = "https://reqres.in/api";

    @Test
    public void getUser() {  

        // GIVEN
        given()
                .contentType(ContentType.JSON)

                // WHEN
                .when()
                .get(BaseURL + "/users/2")

                // THEN
                .then()
                .statusCode(200)
                .body("data.first_name", equalTo("Janet"))
                .log().all();

    }

}

Use Case Examples**:
  - Login authentication: The client needs the server's response before proceeding.
  - Fetching data: The client requires the result immediately to display to the user.
**Use Case Examples**:
  - File upload or processing: The server processes the file and sends a notification when done.
  - Notification systems: Sending push notifications to multiple devices.

TestNG Interview Questions 2025

HOME


Follow the below steps to install TestNG on Eclipse:



The testng.xml file is important because of the following reasons:

groups = { "e2etest", "integerationtest" }
@Test(enabled = false)
listenerclass-name ="com.selenium.testng.ListenerDemo
suitename="TestSuite"thread-count="3"parallel="methods
<parameter name="browser" value="Edge" /> 

Assert.assertEquals(actual value, expected value);
softAssert soft_assert = new softAssert();
soft_assert.assertAll();

6.  What is TestNG Assert and list out some common Assertions supported by TestNG?            

TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it completed the test run without throwing any exception. Some of the common assertions supported by TestNG are:

assertEqual(String actual,String expected)
assertEqual(String actual,String expected, String message)
assertEquals(boolean actual,boolean expected)
assertTrue(condition)
assertTrue(condition, message)
assertFalse(condition)
assertFalse(condition, message)

For more details, click here                                             


7. How to run a group of test cases using TestNG?

Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath.

import org.testng.annotations.Test;
 
public class TestNGGroupDemo {
 
    @Test(alwaysRun = true, groups = { "e2etest", "integerationtest" })
    public void testPrintMessage() {
        System.out.println("This method is run by both e2e and integeration test");
    }
 
    @Test(alwaysRun = true, groups = { "e2etest" })
    public void testE2EMessage() {
        System.out.println("This method is run by e2e test");
    }
 
    @Test(alwaysRun = true, groups = { "integerationtest" })
    public void testingIntegrationMessage() {
        System.out.println("This method is run by integeration test");
    }
 
    @Test(alwaysRun = true, groups = { "acceptancetest" })
    public void testingAcceptanceMessage() {
        System.out.println("This method is run by Acceptance test");
    }
 
    @Test(alwaysRun = true, groups = { "e2etest", "acceptancetest" })
    public void testE2EAndAcceptanceMessage() {
        System.out.println("This method is run by both e2e and acceptance test");
    }
 
    @Test(alwaysRun = true, groups = { "e2etest", "integerationtest", "acceptancetest" })
    public void testE2EAndAcceptanceAndIntegrationMessage() {
        System.out.println("This method is run by e2e, integration and acceptance test");
    }
 
}

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "TestNG Demo">
    <test name = "TestNG Grouping">
        <groups>
            <run>
                <include name = "e2etest" />
            </run>
        </groups>
        <classes>
            <class name = "TestNGGroupDemo" />
        </classes>
    </test>
</suite>

For more details, click here.


8. How to set test case priority in TestNG?

We use priority attribute to the @Test annotations.  If no priority is assigned to a Test Case, then the annotated test methods are, executed as per the alphabetical order of the tests

import org.testng.annotations.Test;

public class TestNGPriorityDemo {

    @Test(priority = 3)
    public static void FirstTest() {
        System.out.println("This is Test Case 1, but after priority Test Case 3");
    }


    @Test(priority = 4)
    public static void SecondTest() {
        System.out.println("This is Test Case 2, but after priority Test Case 4");
    }


    @Test(priority = 2)
    public static void ThirdTest() {
        System.out.println("This is Test Case 3, but after priority Test Case 2");
    }


    @Test(priority = 1)
    public static void FourthTest() {
        System.out.println("This is Test Case 4, but after priority Test Case 1");
    }
}

For more details, click here


9. How can we make one test method dependent on others using TestNG?

Using the dependsOnMethods parameter inside @Test annotation in TestNG we can make one test method run only after the successful execution of the dependent test method. Dependency is a feature in TestNG that allows a test method to depend on a single or a group of test methods. Method dependency only works if the “depend-on-method” is part of the same class or any of the inherited base classes (i.e. while extending a class)

         @Test
            public static void FirstTest() {
                        System.out.println("This is Test Case 1");
            }  
 
          @Test(dependsOnMethods = "FirstTest") 
             public static void SecondTest() {
                        System.out.println("This is Test Case 2 and will be executed after Test Case 1 sucessfully executed");
            } 

           @Test 
           public static void ThirdTest() {
                       System.out.println("This is Test Case 3");
             }  
 
           @Test 
             public static void FourthTest() {
                            System.out.println("This is Test Case 4"); 
         }
}

For more details, click here


10. How to skip a method or a code block in TestNG?

If you want to skip a particular test method, then you can set the ‘enabled’ parameter in the test annotation to false.

@Test(enabled = false) 

By default, the value of the ‘enabled’ parameter will be true. Hence, it is not necessary to define the annotation as true while defining it.

For more details, click here


11. How do you exclude a group from the test execution cycle?

Excluding a group in TestNG denotes that this particular group refrains from running during the execution, and TestNG will ignore it. Additionally, the name of the group that we want to exclude is defined in the XML file by the following syntax:

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
   <test name = "Test Demo"> 
      <groups>
         <run>
            <exclude name = "e2etest"/>
         </run>
      </groups>
      <classes>
         <class name = "com.selenium.testng.TestNGDemo.TestNGGroupDemo"/>
      </classes>   
   </test>
</suite>

By putting our group “e2etest” inside the exclude tag, we are requesting TestNG to ignore the test cases under the group “e2etest”.


12. How to run test cases in parallel using TestNG?

In testng.xml, if we set the ‘parallel’ attribute on the tag to ‘methods’, testNG will run all the ‘@Test’ methods in the tag in a separate thread.

The parallel attribute of suite tag can accept four values:

tests – All the test cases inside tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute in parallel but two methods of two different instances will run in a different thread.

Below is an example to testng.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" thread-count="3" parallel="methods" >
<test name="GoogleTest">
<classes>
<class name="TestNGDemo.ParallelTestDemo">
</class>
</classes>
</test>
</suite>

For more details,click here


13. What is the use of @Listener annotation in TestNG?

A listener is defined as an interface that modifies the default TestNG’s behavior. It allows customizing TestNG reports or logs. There are many types of TestNG listeners available. Here are a few listeners:

  • IAnnotationTransformer 
  • IAnnotationTransformer2 
  • IHookable 
  • IInvokedMethodListener 
  • IMethodInterceptor 
  • IReporter 
  • ISuiteListener 
  • ITestListener 

For more details,  click here


14. How are listeners declared in TestNG?

When you implement one of these interfaces, you can let TestNG know about it in either of the following ways:

  • Using in your testng.xml file.
@Listeners(com.selenium.testng.TestNGDemo.ListenerDemo.class)

Using the@Listeners annotation on any of your test classes.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "TestSuite">
<listeners>
<listener class-name ="com.selenium.testng.TestNGDemo.ListenerDemo"/>
</listeners>
 
<test name ="Test">
<classes>
<class name="com.selenium.testng.TestNGDemo.ListenerTestCases"/>
</classes>
</test>
</suite>

For more details, click here


15. Do TestNG reports need external code to write?

No, there is no need to write any code to generate reports in TestNG. In other words, the report generation happens by default.


16. What are the two reports generated in TestNG?

We can generate the TestNG reports in two ways:

· Emailable Reports
· Index Reports


17. Where is the emailable report generated and saved in TestNG?

Emailable reports are generated under the project folder and test-output subfolder. This report is available as “emailable-report.html” by default.


18. Where is the index report generate and saved in TestNG?

The index report generates under the project folder and test-output subfolder. Moreover, this report is available as “index.html” by default.


19. What is invocationCount in TestNG?

An invocationCount in TestNG is the number of times that we want to execute the same test.

import org.testng.annotations.Test;
public class InvocationCountDemo {
            @Test(invocationCount = 5)
            public void testcase1() {
                        System.out.println("testcase1");
            } 
}

Output
testcase1
testcase1
testcase1
testcase1
testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1

20. How to pass the parameter in the test case through testng.xml file?

TestNG can pass different test data to a test case as arguments which is called parametrization

@Parameters("value")

TestNG.xml looks like this as shown below. Here, the parameter name is the browser name value for the browser is “Chrome”. So, this “Chrome” value is passed to Test as a parameter, and as a result a Google Chrome browser opens.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "TestSuite">
  <test name="ChromeTest">
<parameter name="browser" value="Chrome" />
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGParameterizationDemo">
</class>
</classes>
</test> 
</suite>

For more details, click here

Advanced Selenium Interview Questions and Answers 2025

HOME

Number of Tests * Average Test Time / Number of Nodes = Total Execution Time
 
15      *       45s        /        1        =      11m 15s   // Without Grid
15      *       45s        /        5        =      2m 15s    // Grid with 5 Nodes
15      *       45s        /        15       =      45s       // Grid with 15 Nodes

To know more about the steps to configure Selenium4, please refer to Selenium 4 Grid – Parallel Testing.

(//parentElement/*)[n]

import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
 
public class ProxyDemo {
 
    public static void main(String[] args) {
 
        // Set the proxy server details
        String proxyAddress = "localhost";
        int proxyPort = 8080;
 
        // Create a Proxy object and set the HTTP proxy details
        Proxy proxy = new Proxy();
        proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
 
        // Configure Chrome options with the Proxy object
        ChromeOptions options = new ChromeOptions();
        options.setProxy(proxy);
        options.addArguments("start-maximized");
 
        // Instantiate ChromeDriver with the configured options
        WebDriver driver = new ChromeDriver(options);
 
 
        // Perform your browsing actions using the driver
        driver.get("https://www.google.com");
        System.out.println("Page Title :" + driver.getTitle());
 
        // Close the browser session
        driver.quit();
    }
}

WebDriver driver = new ChromeDriver(); // For Chrome

WebDriver driver = new FirefoxDriver(); // For Firefox

WebDriver driver = new EdgeDriver(); // For Edge

Cucumber Interview Questions and Answers 2025

Last Updated On

HOME

1. What is BDD? Why do we use BDD?

BDD (behavior-driven development ) is an Agile software development process that encourages collaboration among developers, QA, and business participants in a software project.

Why do we use BDD
BDD increases and improves collaboration between various teams involved in the project to easily engage with the product development cycle. We use a simple English language called Gherkins to write test scenarios.


2. What is Cucumber? What are the advantages of Cucumber?

Cucumber is an open-source tool that supports Behavior Driven Development (BDD). It is written in Rugby Language. Cucumber reads executable specification written in plain English language (Gherkins) and validates that the software act as per the executable specifications.

Advantages of Cucumber

  • Cucumber supports different languages like Java.net and Ruby. 
  • It acts as a bridge between the business and technical language. We can accomplish this by creating a test case in plain English text. 
  • It allows the test script to be written without knowledge of any code; it allows the involvement of non-programmers as well. 
  • It serves the purpose of an end-to-end test framework, unlike other tools. 
  • Due to simple test script architecture, Cucumber provides code re-usability.

Please refer to this tutorial for more detailsIntroduction of Cucumber Testing Tool (BDD Tool)


3. What is the programming language used by Cucumber?

The cucumber tool provides support for multiple programming languages such as Java, .Net, Ruby, etc. It can also be integrated with multiple tools such as Selenium, Capybara, etc.

Please refer to this tutorial for more detailsIntroduction of Cucumber Testing Tool (BDD Tool)


4. What is Gherkin?

Gherkin is a set of grammar rules that makes plain text structured enough for Cucumber to understand. 

Gherkin serves multiple purposes:-

  • Unambiguous executable specification
  • Automated testing using Cucumber
  • Document how the system actually behaves

Please refer to this tutorial for more detailsCucumber – What is Gherkin.


5. What are the files required to execute a Cucumber test scenario?

Features
Step Definition
Test Runner


6. What is a Feature File?

A Feature File is a file in which we store features, descriptions of the features and scenarios to be tested. The first line of the feature file must start with the keyword ‘Feature’ followed by the description of the application under test. A feature file may include multiple scenarios within the same file. A feature file has the extension .feature. Below is an example of the Feature file.

Feature: Login to HRM Application 
 
   @ValidCredentials
   Scenario: Login with valid credentials
     
    Given User is on Home page
    When User enters username as "Admin"
    And User enters password as "admin123"
    Then User should be able to login sucessfully

Please refer to this tutorial for more details –  Cucumber – What is Feature File in Cucumber.


7. What are the various keywords that are used in Cucumber for writing a scenario?

Below mentioned are the keywords used for writing a scenario:

  1. Given – It is used to describe the initial context of the scenario.  When the Given step is executed, it will configure the system to a well-defined state, such as creating & configuring objects or adding data to a test database.
  2. When – It is used to describe an event or action. This can be a person interacting with the system or it can be an event triggered by another system.
  3. Then – It is used to describe the expected outcome of the scenario
  4. And/But – If we have several Given’s, When’s, or Then’s, then we can use And /But.

Please refer to this tutorial for more details – Cucumber – What is Feature File in Cucumber.


8. What is the purpose of the Step Definition file in Cucumber?

It is a Java method with an expression, which is used to link it to Gherkin steps. When Cucumber executes a Gherkin step, it will look for a matching step definition to execute. Step definitions can be written in many programming languages.

Feature: Book flight ticket for one-way trip
Scenario: flight ticket for one-way trip from Dublin 
Given  I live in Dublin 
  
@Given ("I live in Dublin") 
public voidVacation()
   {
        System.out.println("I live in Dublin");
   }

Please refer to this tutorial for more details – Step Definition in Cucumber


9. What is the use of the Background keyword in Cucumber?

Background keyword is used to group multiple given statements into a single group. This is generally used when the same set of given statements is repeated in each scenario in the feature file. For example, you need to pass the bearer token in every test. So, this can be done by defining the Given statement as background.

Please refer to this tutorial for more details – Background in Cucumber


10. What is the purpose of the Cucumber Options tag?

The cucumber Options tag is used to provide a link between the feature files and step definition files. Each step of the feature file is mapped to a corresponding method on the step definition file.

Below is the syntax of the Cucumber Options tag:

@CucumberOptions(features="src/test/resources/features/MyHoliday.feature",tags = { "@BookOneWayFlight"})

11. What is TestRunner class in Cucumber?

It is the starting point for JUnit to start executing the tests. TestRunner class is used to provide the link between the feature file and the step definition file.

Below is an example of TestRunner class.

import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
 
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/Feature/MyHoliday.feature", tags = { "@BookOneWayFlight"})
 
public classTestRunner { 
}

Please refer to this tutorial for more details – Cucumber – JUnit Test Runner Class.


12. What is a profile in cucumber?

You can create Cucumber profiles to run a set of features and step definitions. Use the following command to execute a cucumber profile.

Syntax:

cucumber features -p <profile_name>

Example:

cucumber features -p Integration

13. What are hooks in Cucumber?

Hooks are blocks of code that can run at various points in the Cucumber execution cycle

1- Before: executes before the feature file execution.
2- After: executes after the feature file execution.
3- BeforeStep: executes before each step execution.
4- AfterStep: executes after each step execution.

Below is an example of hooks.

public class CucumberHooksExampleDefinitions {
 
    WebDriver driver;
 
    @Before
    public void setup() {
 
        System.out.println("---------------------Before Executing----------------------");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--start-maximized");
        driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    }
 
    @BeforeStep
    public void beforeStepTest() {
        System.out.println("--------------BeforeStep Executing---------------");
    }
 
    @Given("User is on Home page")
    public void userOnHomePage() {
 
        System.out.println("Open Website");
        driver.get("https://opensource-demo.orangehrmlive.com/");
    }
 
    @When("User enters username as {string}")
    public void entersUsername(String userName) throws InterruptedException {
 
        System.out.println("Enter userName");
        driver.findElement(By.name("txtUsername")).sendKeys(userName);
 
    }
 
    @When("User enters password as {string}")
    public void entersPassword(String passWord) throws InterruptedException {
 
        System.out.println("Enter passWord");
        driver.findElement(By.name("txtPassword")).sendKeys(passWord);
 
        driver.findElement(By.id("btnLogin")).submit();
    }
 
    @Then("User should be able to login sucessfully")
    public void sucessfullLogin() throws InterruptedException {
 
        String newPageText = driver.findElement(By.id("welcome")).getText();
        System.out.println("newPageText:" + newPageText);
        assertThat(newPageText, containsString("Welcome"));
 
    }
 
    @AfterStep
    public void afterStepTest() {
        System.out.println("--------------------AfterStep Executing---------------------");
    }
 
    @After
    public void close() {
        driver.close();
        System.out.println("--------------------After Executing----------------------");
    }
}

Please refer to this tutorial for more details – Hooks in Cucumber


14. What are cucumber tags?

Tags are a great way to organize Features and Scenarios. Cucumber tags help in filtering the scenarios. We can tag the scenarios and then run them based on tags.

Below is an example of the tag.

Feature: Sample use of Tags in Cucumber
 
  @ValidCredentials
  Scenario: Login with valid credentials
    
   Given User is on Home page
   When User enters username as "Admin"
   And User enters password as "admin123"
   Then User should be able to login sucessfully

Here, @ValidCredentials is the Tag.

Please refer to this tutorial for more details – Tags in Cucumber.


15. What is the use of features property under the Cucumber Options tag?

Feature property under Cucumber option tag lets Cucumber know the location of Feature Files. As in the below example, the location of the feature file is under src/test/resources/features.

@CucumberOptions(features = "src/test/resources/Feature/MyHoliday.feature")

Please refer to this tutorial for more details – Cucumber – What is Feature File in Cucumber.


16. What is the use of glue property under the Cucumber Options tag?

The glue property lets Cucumber know the location of the Step Definition file. As in the below example, the location of the step definition is “com.cucumber.demo.definitions”.

@CucumberOptions(features = { "src/test/resources/features/MyHoliday.feature" }, glue = {"com.cucumber.demo.definitions" }

17. What is the Scenario Outline in the feature file?

Scenario outline is a way of parameterization of scenarios in Cucumber. It is used to repeat the same tests by passing different values or arguments to Step Definition. Scenario Outline must be followed by the keyword ‘Examples’, which specifies the set of values for each parameter.

Scenario Outline: Book Flight for one-way trip
   
  Given I live in Dublin with adults and kids
  And I want to book one way flight ticket from Dublin to London on 
  When I search online
  Then TripAdvisor should provide me options of flights on 
  And Cost of my flight should not be more than Euro per person
 And Tickets should be refundable
   
 Examples:
  |noOfAdults         |noOfKids         |travelDate    |flightFare    |
  |2                  |  2              |22-Jan-2020   |100           |
  |1                  |  0              |12-Mar-2020   |50            |

Please refer to this tutorial for more details – Data Driven Testing using Scenario Outline in Cucumber


18. What is the purpose of the Examples keyword in Cucumber?

Examples – All scenario outlines have to be followed by the Examples section. This contains the data that has to be passed on to the scenario in Feature File. Scenario Outline must be followed by the keyword ‘Examples’, which specifies the set of values for each parameter.

The example is shown in the previous example.

Please refer to this tutorial for more details – Data Driven Testing using Scenario Outline in Cucumber


19. Should any code be written within the TestRunner class?

No code should be written under the TestRunner class. It should include the tags @RunWith and @CucumberOptions.


20. What is the purpose of a cucumber dry-run?

We use to compile the cucumber feature files and step definitions. If there occur any compilation errors, then it shows them on the console.

@RunWith(Cucumber.class)
@CucumberOptions(dryRun=true)
public class RunCucumberTest {
}

21. List out some of the main differences between Jbehave and Cucumber?

1- Jbehave is Java-based and Cucumber is Ruby-based.
2- Jbehave is story-driven whereas the Cucumber is feature-driven.


22. What are the steps to generate a report in Cucumber?

We run the following command to produce HTML reports.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty", "html:target/cucumber"})
public class RunCucumberTest {
}

Cucumber Version 6.7.0 and above we can create a Cucumber Report by adding a cucumber.properties file in src/test/resources and mention the below instruction in it.

cucumber.publish.enabled=true

Please refer to this tutorial for more details – Cucumber Report Service


23. Does Cucumber comes with an assertion library?

No, Cucumber does not come with an assertion library. It uses assertion from unit testing tools like JUnit, TestNG, JavaScript, RSpec.


24. How to run a Cucumber test using tags in Command-Line?

mvn test -Dcucumber.filter.tags="@BookOneWayFlight"

mvn test -Dcucumber.options="@BookOneWayFlight"

Please refer to this tutorial for more detailsRun Cucumber Test from Command Line.


25. Can we use Selenium with Cucumber?

Yes, we can use Selenium with Cucumber to test a Web Application. Cucumber makes the tests readable for business also. To know more about the Integration of Selenium with Cucumber, refer to this tutorial – Integration of Cucumber with Selenium and JUnit


26. What is DataTable in Cucumber?

Data Tables in Cucumber are used to add multiple parameters in Step Definition in a tabular form rather than putting all the parameters in the Gherkin statement. This is much easier to read and multiple rows of data can be passed in the same step. Data tables from Gherkin can be accessed by using the DataTable object as the last parameter in a Step Definition. Below is an example of DataTable.

Feature: Login to HRM Application 
  
   @ValidCredentials
   Scenario: Login with valid credentials
      
    Given User is on HRMLogin page
    When User enters valid credentials
    |Admin|admin123|
    Then User should be able to login sucessfully and new page open

Please refer to this tutorial for more details – DataTables in Cucumber


27. What is the difference between Scenario Outline and DataTables in Cucumber?

Scenario Outline

  1. The Scenario Outline keyword is used to run the same Scenario multiple times, with different combinations of data.
  2. Cucumber automatically runs the complete test the number of times equal to the number of data in the Test Set.
  3. Example tables always have a header row, because the compiler needs to match the header columns to the placeholders in the Scenario Outline’s steps.
Scenario Outline: Book Flight for one-way trip
   
  Given I live in Dublin with adults and kids
  And I want to book one way flight ticket from Dublin to London on 
  When I search online
  Then TripAdvisor should provide me options of flights on 
  And Cost of my flight should not be more than Euro per person
 And Tickets should be refundable
   
 Examples:
  |noOfAdults         |noOfKids         |travelDate    |flightFare    |
  |2                  |  2              |22-Jan-2020   |100           |
  |1                  |  0              |12-Mar-2020   |50            |

DataTable

  1. No keyword is used to define the test data
  2. This works only for the single step, below which it is defined
  3. Data tables are passed wholesale to the step definitions, and it’s up to the user to interpret them. They don’t necessarily have a header row.
Feature: Login to HRM Application 
  
   @ValidCredentials
   Scenario: Login with valid credentials
      
    Given User is on HRMLogin page
    When User enters valid credentials
    |Admin|admin123|
    Then User should be able to login sucessfully and new page open

28. Can we run Cucumber tests parallelly?

Yes, we can run Cucumber tests parallelly. Cucumber-JVM allows parallel execution across multiple threads since version 4.0.0.

Cucumber Scenarios can be executed in parallel using the JUnit Platform

Cucumber can be executed in parallel using JUnit and Maven test execution plugins

Cucumber can be executed in parallel using TestNG and Maven test execution plugins.

Please refer to this tutorial for more details – Parallel Testing in Cucumber with TestNG.


29. Can we use Cucumber with Rest Assured?

Cucumber is not an API automation tool, but it works well with other API automation tools, like Rest Assured.

Please refer to this tutorial for more details – Rest API Test in Cucumber BDD.

This tutorial gives an idea of various questions that can be asked in an interview. Hope this helps you in the preparation of the Interview.

CI/CD Interview Questions and Answers 2025

HOME

pipeline {
    agent any
 
    stages {
        stage('Test') {
            steps {
                bat "mvn -D clean test"
            }
 
            post {                
                // If Maven was able to run the tests, even if some of the test
                // failed, record the test results and archive the jar file.
                success {
                   publishHTML([
                       allowMissing: false, 
                       alwaysLinkToLastBuild: false, 
                       keepAll: false, 
                       reportDir: 'target/surefire-reports/', 
                       reportFiles: 'emailable-report.html', 
                       reportName: 'HTML Report', 
                       reportTitles: '', 
                       useWrapperFileDirectly: true])
                }
            }
        }
    }
}

Selenium Interview Questions and Answers 2025

HOME

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


driver.findElement(By.xpath("/html/body/form/content"));

Double Slash “//” – Double slash is used to create an XPath with a relative path i.e. the XPath would be created to start selection from anywhere within the document. For example, the below example will select any element in the document which has an attribute named “id” with the specified value “email”.

driver.findElement(By.xpath("//*[@id = 'email']")

For more details, click here


4. How do we can launch the browser using WebDriver?

Firstly, we should instantiate a Chrome/Chromium session by doing the following

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
           
 ChromeOptions options = new ChromeOptions();
 WebDriver driver = new ChromeDriver(options);

The chromedriver is implemented as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

         FirefoxOptions firefoxOptions = new FirefoxOptions();
        WebDriver driver = new FirefoxDriver(firefoxOptions);

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

      EdgeOptions options = new EdgeOptions();
      WebDriver driver = new EdgeDriver(options);

For more details, click here 


5. What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

6. Explain the different exceptions in Selenium WebDriver

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:


1. TimeoutException: This exception is thrown when a command performing an operation does not complete in the expected time.

2. NoSuchElementException: This exception is thrown when an element with given attributes is not found on the web page. Suppose webdriver is trying to click on XPath – “//*[@id=’yDmH0d’]/div/div[2]/div[2]/form/content” which doesn’t exist on that particular web page, then the below exception is displayed – org.openqa.selenium.NoSuchElementException.

3. ElementNotVisibleException: This exception is thrown when the element is present in DOM (Document Object Model), but not visible on the web page.

4. StaleElementException: This exception is thrown when the element is either deleted or no longer attached to the DOM. This exception occurs, when Selenium navigates to a different page, comes back to the same old page, and performs operations on the old page. Technically, it occurs when the element defined in the Selenium code is not found in the cache memory and the Selenium code is trying to locate it. 


7. What are the different types of waits available in WebDriver?

How do you achieve synchronization in WebDriver?

There are three types of wait in Selenium WebDriver

 1.   Implicit Wait – The implicit wait will tell to the web driver to wait for a certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, the web driver will wait for that time before throwing an exception. Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.
We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));

2.    Explicit Wait – An explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and the maximum amount of time before throwing the NoSuchElementException exception. Unlike Implicit waits, explicit waits are applied for a particular instance only.

 Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(2));
  wait.until(d -> revealed.isDisplayed());

3.  Fluent Wait – Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page.

Fluent Wait commands are mainly used when the web elements which sometimes visible in a few seconds and sometimes take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on the requirement.

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

    wait.until(
        d -> {
          revealed.sendKeys("Displayed");
          return true;
        });

For more details, click here 


8. How to set the size of the Window in Selenium WebDriver?

First, fetch the size of the browser window in pixels by the below code Dimension

//Access each dimension individually
int width = driver.manage().window().getSize().getWidth();
int height = driver.manage().window().getSize().getHeight();

//Or store the dimensions and query them later
Dimension size = driver.manage().window().getSize();
int width1 = size.getWidth();
int height1 = size.getHeight();

Now, change the size of the window by using

driver.manage().window().setSize(new Dimension(1024, 768)); 

9. How to set the position of Window in Selenium?

First fetch the coordinates of the top left coordinate of the browser window by

// Store the dimensions and query them later
Point position = driver.manage().window().getPosition();
         int x1 = position.getX();
         int y1 = position.getY();

// Access each dimension individually
int x = driver.manage().window().getPosition().getX();
int y = driver.manage().window().getPosition().getY();

The window can be moved to the chosen position by

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));

10. What is the difference between driver.findElement() and driver.findElements() commands?

FindElement – This method locates the first web element on the current web page matching the criteria mentioned as the parameter.  
If the web element is not found, it will throw an exception – NoSuchElementException. 

driver.findElement(By.xpath("Xpath location"));

FindElements – This method locates all the web elements on the current web page matching the criteria mentioned as parameters. 

If not found any WebElement on the current page as per the given element locator mechanism, it will return the empty list.     

findElements (By arg0):List<WebElement

For more details, click here 


11. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox. The sendKeys type a key sequence in the DOM element even if a modifier key sequence is encountered.

Syntax - sendKeys(CharSequence… keysToSend ) : void
Command – driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

For more details, click here


12. How can we get a text of a web element?

The get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors, etc displayed on the web pages. 

String Text = driver.findElement(By.id(“Text”)).getText();

13. How to input text in the text box without calling the sendKeys()?

//Creating the JavascriptExecutor interface object by Type casting                                     JavascriptExecutor js = (JavascriptExecutor)driver;              

//Launching the Site        
driver.get("https://www.google.com/");                      
js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");

Actions actions = new Actions(driver);
actions.moveToElement(element).click().sendKeys("Selenium Introduction").build().perform();

For more details, click here


14. How to read a JavaScript variable in Selenium WebDriver? 

//To initialize the JS object
JavascriptExecutor JS = (JavascriptExecutor) webdriver;

//To get the site title
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

For more details, click here


15. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

There are some conditions where we cannot handle problems with only WebDriver. Web controls don’t react well to selenium commands. In this kind of situation, we use Javascript. It is useful for custom synchronizations, hiding or showing web elements, changing values, testing flash/HTML5, and so on. 
To do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver.

It providesexecutescript” & “executeAsyncScript methods, to run JavaScript in the context of the currently selected frame or window.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

Script – This is the JavaScript that needs to be executed.

Arguments – It is the arguments to the script. It’s optional
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method 2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate an Alert Pop window in Selenium
5. To refresh the browser window using Javascript
6. To get inner text of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium


For more details, click here


16. How To Highlight Element Using Selenium WebDriver?

By using the JavascriptExecutor interface, we could highlight the specified element

//Create the JavascriptExecutor interface object by Type casting               
JavascriptExecutor js = (JavascriptExecutor)driver; 

//Higlight element - Total PageCount
WebElement TotalCount = driver.findElement(By.id("Stats1"));
js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount); 

For more details, click here


17. List some scenarios that we cannot automate using Selenium WebDriver?


18. How can you find if an element is displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()
isDisplayed():
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
isSelected():
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected(); 
isEnabled():
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

19. Explain how you can switch back from a frame?

To switch back from a frame use the method defaultContent().  

driver.switchTo().defaultContent(); 

20. What is the difference between getWindowhandles() and getwindowhandle() ?

getwindowhandles(): It is used to get the address of all the open browser and its return type is Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is and return type is string.

For more details, click here


21. How to select the value in a dropdown?

To perform any operation on DropDown, we need to do 2 things:-

1) Import package org.openqa.selenium.support.ui.Select 
2) Create a new Select object of the class Select

Select oSelect = new Select());
Different Select Commands
Select yselect = new Select(driver.findElement(By.id("year")));
yselect.selectByValue("1988");
 Select mselect = new Select(driver.findElement(By.id("month")));
 mselect.selectByVisibleText("Apr");
Select bselect = new Select(driver.findElement(By.name("birthday_day")));
bselect.selectByIndex(8);

For more details, click here


22. How to switch to a new window (new tab) that opens up after you click on a link?

If you click on a link in a web page and it opens a new window, but WebDriver will not know which window the Operating system consider active. To change the WebDriver’s focus/ reference to the new window we need to use the switchTo() command. driver.switchTo().window();

Here, ‘windowName’ is the name of the window you want to switch your reference to.

In case you do not know the name of the window, then you can use the driver.getWindowHandle() command to get the name of all the windows that were initiated by the WebDriver. Note that it will not return the window names of browser windows which are not initiated by your WebDriver.

Once you have the name of the window, then you can use an enhanced for loop to switch to that window. Look at the piece of code below.

String handle= driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) 
{
driver.switchTo().window(handle); 
}

//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
 assert driver.getWindowHandles().size() == 1;

 //Click the link which opens in a new window
 driver.findElement(By.linkText("new window")).click();

 //Wait for the new window or tab
 wait.until(numberOfWindowsToBe(2));
  
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break; 
    } 
}
  
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));  

For more details, click here


23. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

24. How to delete Browser Cookies with Selenium Web Driver?

driver.Manage().Cookies.DeleteAllCookies();
driver.manage().deleteCookieNamed("cookie_name");
// Get the cookie
Cookie cookie = driver.manage().getCookieNamed("cookie_name");

// Delete the specific cookie
driver.manage().deleteCookie(cookie);

25. What are the different types of navigation commands?

  • driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history.
  • driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history.
  • driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements.
  • driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.

For more details, click here


26. How can we handle Web-based Pop-ups or Alerts in Selenium?

To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.

  • dismiss(): To click on Cancel button.
  • accept(): To Click on OK button.
  • getText(): To get the text which is present on the Alert.
  • sendKeys(): To enter the text into the alert box.

For more details, click here


27. What are the ways to refresh a browser using Selenium WebDriver?

1. Using driver.navigate().refresh() command.
2. Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
3. Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
4. Using sendKeys(Keys.F5) on any textbox on the webpage.        



28. What are the different mouse actions that can be performed?

The different mouse events supported in selenium are
1. click(WebElement element)
2. doubleClick(WebElement element)
3. contextClick(WebElement element)
4. mouseDown(WebElement element)
5. mouseUp(WebElement element)
6. mouseMove(WebElement element)
7. mouseMove(WebElement element, long xOffset, long yOffset)

For more details, click here


29. Write the code to double-click an element in selenium?

To double-click an element in Selenium, you can use the Actions class, which provides the doubleClick() method. The code to double-click an element in selenium is mentioned below

driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement clickable = driver.findElement(By.id("clickable"));
new Actions(driver)
.doubleClick(clickable)
.perform();

30. Write the code to right-click an element in selenium?

To right-click an element in Selenium, you can use the Actions class, which provides the contextClick() method for performing a right-click action. Below is an example:

 driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement clickable = driver.findElement(By.id("clickable"));
new Actions(driver)
.contextClick(clickable)
.perform();

31. How to mouse hover an element in selenium?

// Launch the URL
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement hoverable = driver.findElement(By.id("hover"));
	     
new Actions(driver)
.moveToElement(hoverable)
.perform();

Using the Action class, drag and drop can be performed in selenium.

// Launch the URL
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");

WebElement hoverable = driver.findElement(By.id("hover"));
	     
new Actions(driver)
.moveToElement(hoverable)
.perform();

    Or
driver.get("https://www.selenium.dev/selenium/web/mouse_interaction.html");
 
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id("droppable"));
new Actions(driver)
.dragAndDrop(draggable, droppable)
.perform();

33. How can we capture screenshots in selenium?

Using the getScreenshotAs method of the TakesScreenshot interface, we can take the screenshots in selenium.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));


Set<Cookie> cookies = driver.manage().getCookies();
driver.manage().getCookieNamed(arg0);
Cookie cookie = new Cookie("cookieName", "cookieValue");
driver.manage().addCookie(cookie);
driver.manage().deleteCookieNamed("cookieName");
driver.manage().deleteAllCookies();


Advanced Selenium Interview Questions and Answers