interview questions
interview questions
25. How do you remove all occurrences of a given character from an input string in Java?
The String class doesn’t have a method to remove characters. The following example code shows how to use the replace() method to create a new string
without the given character:
String str1 = "abcdABCDabcdABCD";
System.out.println(str1); // bcdABCDbcdABC
26. How do you get distinct characters and their count in a string in Java?
You can create the character array from the string. Then iterate over it and create a HashMap with the character as key and their count as value. The following
example code shows how to extract and count the characters of a string:
String str1 = "abcdABCDabcd";
Selenium:
11. What are the different types of Locator Strategy supported by Selenium?
Selenium supports almost all types of locators.
27. What is an alternative option to driver.get() method to open an URL in Selenium Web Driver?
Another way to open a URL in Selenium WebDriver is by using the driver.navigate().to() method instead of driver.get().
// Quit
driver.quit();
}
}
How to retrieve CSS properties of an element?
To retrieve CSS properties of an element in Selenium WebDriver, you can use the getCssValue() method. Here’s a simple step-by-step method:
1. Find the Element: Use a locator to identify the web element (e.g., By.id(), By.className()).
2. Use getCssValue(): Call the getCssValue("property-name") method on the found element to get the value of the desired CSS property.
// Retrieve the background color of an element with ID "header"
String backgroundColor = driver.findElement(By.id("header")).getCssValue("background-color");
This code finds the element with ID "header" and retrieves its background color. You can replace "background-color" with any other CSS property name to
get its value.
Answer:
The inline frame, or iframe, is an element of HTML that puts another webpage within the parent page. There are five different ways to handle an iframe in
Selenium WebDriver:
Answer:
File upload in Selenium is an automated process that can be done easily by using the sendKeys() method.
But candidates should also be able to explain the two additional methods using the AutoIT tool and Robot Class.
1. Upload files using sendKeys: This method is an inbuilt file upload feature with the following syntax:
upload_file.sendKeys("C:/Users/Sonali/Desktop/upload.png");
Answer:
In Selenium, the Robot class is a Java-based utility class that lets the tester automate tasks that can’t be done using Selenium’s built-in methods – like simulating
keyboard and mouse interactions on-screen for test automation and self-running demos.
Cucumber
What is the purpose of Cucumber hooks, and how are they used in test execution?
Cucumber hooks are code blocks used for setup tasks in test execution. They help set up the test environment, handle errors, and ensure reusability. Hooks are
defined with annotations or similar constructs and executed at specific points during the test lifecycle, such as before or after scenarios, features, or the entire
test run. They allow you to perform actions like setting up test data, initializing resources, cleaning up after execution, and handling exceptions. Hooks provide
flexibility and consistency in managing and executing the test environment.
importorg.junit.runner.RunWith;
importcucumber.api.CucumberOptions;
importcucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features="Features",glue={"StepDefinition"})
A cucumber scenario outline example is a template for creating various scenarios from a collection of input values. The scenario outline is a framework for
building a collection of connected scenarios with similar actions but distinct input values. The different input values that will be used to produce the methods are
represented by placeholders referred to as "sample tables." Consider the following example of a login function that accepts various usernames and passwords:
Scenario Outline: User logs in with valid credentials
Given the user is on the login page
When they enter "<username>" and "<password>"
And they click the login button
Then they should be redirected to the dashboard
Examples:
| username | password |
| user1 | pass1 |
| user2 | pass2 |
| user3 | pass3 |
How do you use Cucumber hooks?
A Cucumber Hook is executed at specific times during the Cucumber test cycle. Hooks are used to perform post-actions after a scenario or step has been
completed and to set up preconditions before they are met. Many hook annotations are provided by Cucumber, which can be used to specify the intended
behavior. A few are listed below.
1. @Before: This hook is executed before each scenario or scenario step. It can be used to do any required setup tasks or to set up the test
environment.
2. @After: This hook is used to determine whether a scenario or a step in a scenario is to be executed. It can be used to teardown the test
environment or perform cleanup operations.
3. @BeforeStep - It is used before each step in a scenario. It can be used to carry out particular tasks before each stage is carried out.
4. @AfterStep: In a scenario, this hook is used after each step. It can be used to carry out particular tasks upon the completion of each stage.
3. Set up the Jenkins task to use a build script or the command line to run the Cucumber tests.
4. Set up the Cucumber plugin in the Jenkins job to generate Cucumber reports.
5. You can either manually start the Jenkins task or schedule it to execute at a particular time.
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean install'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
post {
always {
cucumber htmlReports: true, jsonReports: true
}
}
}
}
}
This Jenkinsfile creates and tests a Maven-based Cucumber project and uses the Cucumber plugin to produce HTML and JSON reports. This file can be modified
to suit the needs of your project.
API Testing:
1. If I want to test any api , how I will develop a request for the same ? List the core components of an HTTP request.
2. An HTTP request consists of five elements:
A Uniform Resource Identifier (URI). This element identifies the resource on the server.
A request header. This element carries the metadata for the message. The metadata could be a format supported by the client, message body
format, browser or client type, cache settings, etc.
Request body. This element indicates the resource representation or message content.
1xx: Informational
100 Continue: The initial part of a request has been received and has not yet been rejected by the server.
101 Switching Protocols: The server is switching protocols as requested by the client.
2xx: Success
200 OK: The request has succeeded, and the server has returned the requested data (or acknowledgement for methods like POST).
201 Created: The request has been fulfilled, resulting in the creation of a new resource.
204 No Content: The server successfully processed the request, but is not returning any content.
3xx: Redirection
301 Moved Permanently: The requested resource has been assigned a new permanent URI.
302 Found: The resource is temporarily located at a different URI, indicated in the response.
304 Not Modified: The resource has not been modified since the last request, allowing the cached version to be used.
4xx: Client Error
400 Bad Request: The server cannot process the request due to a client error (e.g., malformed request syntax).
401 Unauthorized: Authentication is required and has failed or has not yet been provided.
404 Not Found: The server cannot find the requested resource, indicating that it may not exist.
5xx: Server Error
500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server.
503 Service Unavailable: The server is currently unable to handle the request due to temporary overload or maintenance of the server.
1. Response Time – This measures the time taken by the API to process a request and provide a response. Faster response times indicate better
performance.
2. Throughput – This metric evaluates the number of API requests handled within a specific time frame, reflecting the system’s ability to manage high
traffic.
3. Error Rate – The percentage of API requests that result in failure or errors is tracked to assess reliability.
4. Latency – The time delay experienced from the moment a client sends a request to the server until the response begins, which impacts user
experience.
5. Scalability – This parameter evaluates the API’s ability to maintain performance levels under increasing load or simultaneous user requests.
6. Resource Utilization – Monitoring CPU, memory, and network usage gives insight into the efficiency of the API under varying loads.
Karate:
Write the following line of Code under userDetails.feature file that we created in Step #5:
Feature: fetching User Details
Scenario: testing the get call for User Details
@Karate.Test
Feature("Json Compare")
@Test
Restassured
reqSpec.baseUri("http://localhost:8080")
reqSpec.basePath("/employees");
In the context of object-oriented programming languages, method chaining is used to invoke multiple method calls. Each method returns an object, which allows
multiple calls to be chained into a single line that doesn’t require variables to hold interim results.
In REST Assured, it looks like this:
given()
.baseUri(baseUri)
.queryParam(parameterName, parameterValues)
.accept(contentType).
.when()
.then();
12. Write a code that tests REST API using REST Assured.
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
@Test
RestAssured.baseURI = "http://localhost:8080/employees/get";
//Provide HTTP method type - GET, and URL to get all employees
SQL
Join Operation
When you have information about a single object or entity spread across multiple tables, you can use a join operation to combine this information into a single
table. Join operations work by matching the data in a specific column between two or more tables and then combining the rows from these tables into a new
table. Different types of join operations determine how data is matched and combined. You can retrieve a piece of complete information about an object or
entity using join operations from multiple tables.
Example:
CREATE TABLE employees (
employee_id INT,
employee_name VARCHAR(50),
department_id INT
);
Output:
Write a query to find the names of employees that begin with ‘S’
if we want to count the number of employees in each department and list them in
descending order, we would use:
25. Write an SQL query to fetch employee names having a salary greater than or
equal to 5000 and less than or equal to 10000.
Here, we will use BETWEEN in the ‘where’ clause to return the EmpId of the
employees with salary satisfying the required criteria and then use it as a subquery to
find the fullName of the employee from the EmployeeDetails table.
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
At times, you might need to retrieve data from three or more tables at once. A multi-table join requires consecutive JOIN operations: the first and second
tables are joined to form a virtual table and then the third table is joined to this virtual table. Let's take a look at three tables.
Output:
Another type of join in SQL is a SELF JOIN, which connects a table to itself. In order to perform a self-join, it is necessary to have at least one column (say X)
that serves as the primary key as well as one column (say Y) that contains values that can be matched with those in X. The value of Column Y may be null in
some rows, and Column X need not have the exact same value as Column Y for every row.
For instance, we might wish to display results that only include employees with their managers. By using table aliases and a self-join, this can be
accomplished easily.
Output:
Jira:
A Software bug
A Help-desk Ticket
5.
To start Jenkins,
Firstly, open the command prompt
Secondly, navigate to the directory to locate Jenkins war
Lastly, run the following command:
D:>java -jar Jenkins.war
18.
If in a pipeline, one job works well, but the other fails, what would be your
next step?
Hide Answer
You can simply restart the pipeline from the point it failed by using “restart from
stage”.