Sunday, 27 August 2023

API Questions

Question: What is API

Answer: API stands for Application Programming Interface. It is a set of rules and protocols that allows different software applications to communicate with each other. APIs define the methods and data formats that developers can use to request and exchange information between applications, services, or systems.

Question: API Examples

Answer: 

API Call      Action

GET /users    List all users 

GET /users?name={username} Get user by username

GET /users/{id} - Get user by ID 

GET /users/{id}/configurations   Get all configurations for user

POST /users/{id}/configurations   Create - a new configuration for user

DELETE /users/{id}/configurations/{id}  Delete configuration for user

PATCH /users/{id}/configuration/{id}  Update configuration for use

Question: Explain API Gateway

Answer: An API Gateway is a server or service that acts as an intermediary between an application or client and a collection of microservices or backend services.

It serves as a central entry point for managing and routing requests to various backend services, while also providing a range of capabilities to enhance the security, performance, and functionality of APIs.

Question: Web Services

Answer: Web services are a standardized way for software applications to communicate and exchange data over the internet or other network protocols. They provide a set of rules and protocols that enable different systems, written in different programming languages and running on different platforms, to interact with each other seamlessly. Web services allow for the integration of disparate systems and enable them to work together to achieve specific tasks or share data.


Types of Web Services:

  1. SOAP Web Services: These follow the SOAP protocol and are known for their strict standards and features like built-in security and reliability. They use XML for message formatting.


  2. RESTful Web Services: REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful web services use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources, making them simple and lightweight.


  3. JSON-RPC and XML-RPC: These are remote procedure call (RPC) protocols that allow clients to invoke methods or functions on a remote server using JSON or XML as the message format.


  4. GraphQL: GraphQL is a query language for APIs that allows clients to request exactly the data they need, minimizing over-fetching and under-fetching of data.

Question: Differences between SOAP and REST API

Answer: 1.SOAP stands as Simple Object Access Protocol. REST stands as Representational State Transfer.


2.SOAP is a protocol. REST is an architectural pattern.


3.SOAP can work with XML format. In SOAP all the data passed in XML format. REST permit different data format such as Plain text, HTML, XML, JSON etc. But the most preferred format for transferring data is in JSON.

Question: How do you handle error handling and exception testing in API testing?

Answer: Handling error handling and exception testing in API testing is crucial to ensure that an API behaves correctly when errors or exceptional conditions occur. This testing helps verify that the API returns appropriate error responses and handles exceptional situations gracefully. Here's how you can handle error handling and exception testing in API testing:

1. Identify Error Scenarios:

   - Begin by identifying the potential error scenarios specific to the API you are testing. Common error scenarios include invalid input data, authentication failures, server errors, and resource not found errors.

2. Create Test Cases for Error Scenarios:

   - Develop test cases that intentionally trigger these error scenarios. For example:

     - Sending invalid or missing parameters.

     - Using incorrect authentication credentials.

     - Simulating server-side errors or timeouts.

     - Requesting non-existent resources.

3. Expected Error Responses:

   - Determine the expected error responses for each error scenario. This includes the HTTP status code, response body content, and headers. Refer to the API's documentation to understand the expected error format.

4. Automation:

   - Implement automation scripts to execute these test cases systematically. Automation helps ensure that error scenarios are consistently tested and that the expected error responses are verified.

5. Assertions:

   - In your test automation framework, define assertions to check whether the received error response matches the expected response. Assertions should include:

     - Verifying the correct HTTP status code (e.g., 400 for bad request, 401 for unauthorized).

     - Validating the error message and error code in the response body.

     - Checking response headers, if relevant.

6. Edge Cases:

   - Consider testing edge cases to ensure that the API handles extreme or boundary conditions correctly. For example, if an API accepts numeric values, test the minimum and maximum allowed values.

7. Negative Testing:

   - Negative testing involves testing scenarios where unexpected or invalid data is provided to the API. For example, sending a string to an API that expects a number. Ensure that the API responds appropriately and provides informative error messages.

8. Rate Limiting and Throttling:

   - If the API has rate limiting or throttling mechanisms, create tests to verify that these mechanisms are enforced correctly. Test scenarios where the rate limit is exceeded and ensure that the API responds with the appropriate rate-limiting error.

9. Testing Error Recovery:

   - For scenarios involving temporary errors, such as network issues or server timeouts, test the API's ability to recover gracefully. Retry requests after temporary errors to confirm that the API eventually succeeds when the issue is resolved.

10. Logging and Monitoring:

    - Set up logging and monitoring to capture error responses and exceptions during testing. This helps identify issues that may not be immediately visible during test execution.

11. Documentation and Reporting:

    - Document the error scenarios, expected responses, and test results. Create clear and concise reports, including details of any failures or deviations from the expected behavior.

12. Regression Testing:

    - Include error and exception test cases in your regression testing suite to ensure that error handling remains effective as the API evolves over time.

By systematically testing error handling and exception scenarios in your API, you can ensure that the API behaves reliably and provides meaningful error information to users and clients. This helps improve the overall quality and resilience of the API.

Question: How do you handle authentication in API testing?

Answer: Handling authentication in API testing is essential to ensure that only authorized users or applications can access the API's resources and functionality. Authentication mechanisms vary depending on the API and its security requirements. Here are some common methods for handling authentication in API testing:

1. API Key Authentication:

   How it works: The client includes an API key in the request header, query parameter, or request body. The server validates the API key to grant or deny access.

   When to use: API key authentication is simple and suitable for public APIs or when you want to track usage.

2. Token-based Authentication (e.g., OAuth2):

   How it works: Clients obtain access tokens by authenticating with the authorization server. They then include these tokens in API requests. The server validates the token to grant or deny access.

   When to use: Token-based authentication is commonly used for securing APIs that require user authentication, access control, and permissions management.

3. Username and Password Authentication:

   How it works: Clients include a username and password in the request header or request body. The server validates the credentials.

   When to use: This method is used for authenticating users with their credentials. It's commonly used in API testing for services that provide user-specific data or actions.

4. Bearer Token Authentication:

   How it works: Clients include a bearer token in the request header's `Authorization` field, typically in the format "Bearer token_value."

   When to use: Bearer token authentication is commonly used with OAuth2 or token-based authentication systems.

5. Basic Authentication:

   How it works: Clients include a username and password in the request header, encoded in Base64 format. For example, "Authorization: Basic base64(username:password)."

   When to use: Basic authentication is a simple method often used with HTTP or when a more secure method like OAuth2 is not required.

6. API Secret and Signature Authentication:

   How it works: Clients send a request with an API key and a unique signature generated based on the request parameters and a secret key. The server verifies the signature.

   When to use: This method is suitable for securing sensitive operations and is common in payment gateway APIs.

When conducting API testing with authentication, here are some best practices to consider:

Test with Valid Credentials: Start by testing with valid credentials to ensure that the authentication process works correctly.

Test with Invalid Credentials: Test scenarios where authentication fails, such as incorrect passwords, expired tokens, or missing API keys, to ensure proper error handling.

Test with Different Authentication States: Test with different authentication states, such as authenticated, unauthenticated, and partially authenticated, to verify that access is granted or denied as expected.

Use Test Data: Create test accounts or users specifically for testing purposes to avoid affecting production data.

Parameterization: Parameterize authentication credentials and tokens, so you can easily switch between different test scenarios and environments.

Secure Storage: Ensure that sensitive authentication credentials and tokens are securely stored and managed, especially in automated test scripts.

Token Refresh: If using token-based authentication, include tests for token refresh mechanisms to ensure uninterrupted access during longer test scenarios.

By following these best practices and using the appropriate authentication method, you can effectively test the security and functionality of APIs in various scenarios while safeguarding sensitive data and ensuring proper access control.

Question: Can you describe the typical components of an API request and response?

Answer: API requests and responses consist of various components that facilitate the communication between a client (the entity making the request) and a server (the entity processing the request). These components help define the structure and behavior of the interaction. Here are the typical components of an API request and response:

API Request Components

1. HTTP Method (or Verb): This specifies the type of action to be performed on the resource. Common HTTP methods include GET (retrieve data), POST (create a new resource), PUT (update a resource), DELETE (remove a resource), and more.

2. Endpoint (URL): The endpoint is the specific URL or URI (Uniform Resource Identifier) that the client sends the request to. It identifies the resource or service being accessed.

3. Headers: Request headers contain additional information about the request, such as the content type, authentication credentials, caching directives, and more. Some common headers include:

  •    Content-Type: Describes the format of the request body (e.g., JSON, XML).
  •    Authorization: Contains authentication tokens or credentials.
  •    Accept: Specifies the desired response format.
  •    User-Agent: Provides information about the client making the request.

4. Parameters (Query or Path Parameters): Parameters are used to send additional data to the server, often to filter, sort, or customize the response. Query parameters are included in the URL (e.g., `?param=value`), while path parameters are part of the URL's path (e.g., `/resource/{id}`).

5. Request Body (Payload): The request body contains the data that the client sends to the server, typically in JSON, XML, or other formats. It is used for operations like creating or updating resources.

6. Authentication: In some cases, API requests require authentication, which may involve API keys, tokens, or username/password combinations, depending on the authentication method used.

API Response Components:

1.HTTP Status Code: The status code is a three-digit number that indicates the outcome of the request. Common status codes include:

   - 200 (OK): Successful request with a response.

   - 201 (Created): The request resulted in the creation of a new resource.

   - 204 (No Content): The request was successful, but there is no response body.

   - 400 (Bad Request): The request was malformed or had invalid parameters.

   - 401 (Unauthorized): Authentication is required or failed.

   - 404 (Not Found): The requested resource does not exist.

   - 500 (Internal Server Error): An error occurred on the server.

2. Headers: Response headers convey metadata about the response, such as the content type, server information, and caching directives.

3. Response Body: The response body contains the data returned by the server. It is often in JSON, XML, or other formats, depending on the API's design.

4. Error Messages: In case of errors or exceptions, the response body may include error messages or details explaining what went wrong. These messages can help developers diagnose and handle issues.

5. Pagination Information: For APIs that return large sets of data, pagination information may be included in the response to indicate how to retrieve additional results (e.g., page number, page size).


Question: HTTP Request Methods

Answer: GET

It fetches the information from the server. Moreover, it is the most commonly used method which does not have a request body. Every time you open a website, the Get request fires to retrieve the website contents. Additionally, it is equivalent to the

POST

It works to send data to the server. User may add or update data using the Post request. They send the information that needs to update in the request body.

PUT

It is similar to the Post method since it updates the data. The only difference is that we use it when we have to replace an existing entity completely

PATCH

It s again similar to Post and Put methods, but user use it when they have to update some data partially. Moreover, unlike the Post and Put methods, user may send only the entity that needs updation in the request body with the Patch method.

HEAD

It is similar to the Get method, but it retrieves only the header data and not the entire response body. User use it when they need to check the document's file size without downloading the document.

DELETE

It deletes the server's representations of resources through the specific URL. Additionally, just like the Get method, it does not have a request body.

OPTIONS

It is not a widely used method when compared to other ones. It returns data specifying the different methods and the operations supported by the server at the


Question: What is Latency in API testing?

Answer: Latency refers to the response time or the delay taken by the request to reach the server. We need to ensure that the latency involved in reaching the server is minimum as higher the latency, greater is the impact in the application’s speed and performance.


Question:  Key components of ReadyAPI and how they contribute to API testing
Answer: Certainly! ReadyAPI is a comprehensive API testing tool that offers various key components to facilitate API testing and ensure the quality of web services. The key components of ReadyAPI and their contributions to API testing are as follows: 1. Projects: A project in ReadyAPI serves as a container for all the artifacts related to API testing. It allows you to organize your test cases, test suites, and other resources in a structured manner. Projects help maintain a logical separation of different APIs or services being tested, making it easier to manage and execute tests.

2. TestCases: Test cases are at the core of API testing in ReadyAPI. They represent individual tests or scenarios that you want to execute. You can create multiple test cases within a project to cover various aspects of API functionality and behavior.

3. Test Suites: Test suites are collections of test cases that can be executed together. They allow you to group related tests and define the order in which they should run. This is useful for creating comprehensive test scenarios that involve multiple API endpoints or interactions.

4. Requests: Requests represent the actual API calls you want to make during testing. ReadyAPI supports both REST and SOAP requests. You can configure request parameters, headers, authentication, and more. Requests are essential for simulating interactions with the API under test.

5. Assertions: Assertions are used to validate the response data from API calls. ReadyAPI offers a wide range of assertion types, such as status code assertions, content assertions, and schema assertions. Assertions help ensure that the API behaves as expected and that the data returned meets your criteria.

6. Data Sources: Data sources enable data-driven testing in ReadyAPI. You can connect test cases to various data sources like Excel, databases, or CSV files. This allows you to execute the same test case with different input data, making your testing more thorough and efficient.

7. Environments: Environments in ReadyAPI help manage variables and configurations that might change across different environments (e.g., development, staging, production). By switching between environments, you can easily adapt your test cases to various deployment scenarios.

8. Scripting: ReadyAPI provides scripting support using Groovy, which allows you to add custom logic and automation to your test cases. You can use scripts for tasks like dynamic data generation, complex test case flow control, or custom validations.

9. Reports: ReadyAPI generates detailed reports after test execution. These reports provide insights into the test results, including pass/fail status, response data, and logs. Reports are crucial for tracking the health of your APIs and debugging any issues.

10. Integration: ReadyAPI seamlessly integrates with various tools and platforms, including version control systems, continuous integration/continuous deployment (CI/CD) pipelines, and bug tracking systems. This integration streamlines collaboration and automation in the API testing process.
In summary, ReadyAPI's key components work together to provide a comprehensive and organized approach to API testing. It allows testers to create, manage, execute, and analyze API tests effectively, ensuring the reliability and quality of web services.

Question: HTTP Response Status Codes

Answer:

1xx
informational response, request was received, continuing process
100
Continue: The client can continue with the request as long as it doesn't get rejected.
101
Switching Protocols: The server is switching protocols.
102
Processing, It indicates that the server has received and is processing the request, but no response is available yet.
103
Early Hints, it primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.

2xx
Success, request was successfully received, understood, and accepted
200
OK: The request succeeded
201
Created: The request succeeded, and a new resource was created as a result. This is typically the response sent after POST requests, or some PUT requests.
202
Accepted: Request accepted for processing, but in progress
203
Non-Authoritative Information: The information in the entity header is not from an original source but a third-party
204
No Content- Response with status code and header but no response body
205
Reset Content- The form for the transaction should clear for additional input
206
Partial Content- Response with partial data as specified in Range header
207

Multi-Status, Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
3xx
Redirection, further action needed in order to complete the request
300
Multiple Choices: Response with a list for the user to select and go to a location
301
Moved Permanently: Requested page moved to a new url
302
Found: Requested page moved to a temporary new URL
303
See Other: One can find the Requested page under a different URL
305
Use Proxy: Requested URL need to access through the proxy mentioned in the Location header
307
Temporary Redirect: Requested page moved to a temporary new URL
308
Permanent Redirect: This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header.

4xx
Client Error, request contains bad syntax or cannot be fulfilled
400
Bad Request: Server unable to understand the request
401
Unauthorized: Requested content needs authentication credentials
403
Forbidden: Access is forbidden
404
Not Found: Server is unable to find the requested page
405
Method Not Allowed: Method in the request is not allowed
407
Proxy Authentication Required: Need to authenticate with a proxy server
408
Request Timeout: The request took a long time as expected by the server
409
Conflict: Error in completing request due to a conflict
411
Length Required: We require the "Content-Length" for the request to process
415
Unsupported Media Type: Unsupported media-type
417
Expectation Failed, it means the expectation indicated by the Expect request header field cannot be met by the server.
421
Misdirected Request, request was directed at a server that is not able to produce a response.
423
Locked, the resource that is being accessed is locked
429
Too Many Requests,user has sent too many requests in a given amount of time

5xx
Server Error, the server failed to fulfil an apparently valid request
500
Internal Server Error: Request not completed due to server error
501
Not Implemented: Server doesn't support the functionality
502
Bad Gateway: Invalid response from an upstream server to the server. Hence, the request not complete
503
Service Unavailable: The server is temporarily down
504
Gateway Timeout: The gateway has timed out
505
HTTP Version Not Supported: Unsupported HTTP protocol version
507
Insufficient Storage, method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the
511
Network Authentication Required, it indicates that the client needs to authenticate to gain network access

Question: Explain restassured api testing in java

Answer: RestAssured is a Java library that provides a domain-specific language (DSL) for testing RESTful APIs. It simplifies the process of writing and validating API tests by offering a fluent and expressive syntax. RestAssured allows you to perform various HTTP operations like GET, POST, PUT, DELETE, etc., and validate the response against expected values using assertions.


Dependency -

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.3.2</version>

    <scope>test</scope>

</dependency>


example : -

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

import org.testng.annotations.Test;


public class APITest {

  @Test

  public void testGETRequest() {

  given()

    .baseUri("https://jsonplaceholder.typicode.com")

    .basePath("/posts/1")

  .when()

    .get()

  .then()

    //.log().body();

    .statusCode(200)

    .body("userId"equalTo(1))

    .body("id"equalTo(1));

  }

}


Question: Various methods in restassured api testing in java

Answer: 

1. Setting Up Base URI and Base Path:

   `baseURI(String uri)`: Sets the base URI for all requests.

  `basePath(String path)`: Sets the base path for all requests.


2. Request Specification:

    `given()`: Starts building the request specification.

    `given().config(RestAssured.config())`: Configures the request specification using a given RestAssured configuration.

    `given().auth().basic(username, password)`: Specifies basic authentication credentials.

    `given().contentType(ContentType.JSON)`: Sets the content type of the request.

    `given().header(String name, String value)`: Adds a header to the request.

    `given().body(Object object)`: Sets the request body.


3. HTTP Methods:

    `get(String path)`: Performs a GET request.

   `post(String path)`: Performs a POST request.

    `put(String path)`: Performs a PUT request.

    `delete(String path)`: Performs a DELETE request.

   `patch(String path)`: Performs a PATCH request.


4. Response Specification:

    `then()`: Starts building the response specification.

   `then().statusCode(int statusCode)`: Validates the status code of the response.

   `then().contentType(ContentType contentType)`: Validates the content type of the response.

   `then().body(String path, Matcher<?> matcher)`: Validates the response body using a Hamcrest matcher.

   `then().extract().path(String path)`: Extracts a value from the response body using a JSON path expression.


5. Assertions:

   `assertThat()`: Performs assertions on the response using Hamcrest matchers.


6. Logging:

   `log().all()`: Logs all request and response details.

   `log().ifValidationFails()`: Logs request and response details only if validation fails.

  `log().ifError()`: Logs request and response details only if an error occurs.


7. Extracting Response Data:

   `extract()`: Extracts data from the response.

   `extract().response()`: Extracts the entire response.

   `extract().path(String path)`: Extracts a value from the response body using a JSON path expression.

   `extract().jsonPath()`: Creates a JsonPath object for parsing JSON response body.


8. Query Parameters and Path Parameters:

   `queryParam(String name, Object... values)`: Adds query parameters to the request.

  `pathParam(String name, Object value)`: Adds path parameters to the request.


9. Cookies:

   `cookie(String name, String value)`: Adds a cookie to the request.

  `cookies(Map<String, ?> cookies)`: Adds multiple cookies to the request.


10. Filters:

    `filter(Filter filter)`: Adds a filter to the request.


11. Error Handling:

    `when().error()` : Handles HTTP error responses.

    `exception(Exception.class)`: Specifies exceptions to be thrown during request specification building.


Question: How do you log request and response details in RestAssured?

Answer: You can log request and response details in RestAssured using methods like log().all(), log().ifValidationFails(), and log().ifError().


Question:  What is RestAssured?

Answer: RestAssured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. It simplifies the process of testing RESTful web services and supports various HTTP methods like GET, POST, PUT, DELETE, etc.

Question: How do you add RestAssured to your Java project
Answer: You can add RestAssured to your Java project by including the dependency in your project's pom.xml file if you're using Maven or in the build.gradle file if you're using Gradle. Here's an example for Maven:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>

Question: How do you perform a simple GET request using RestAssured?
Answer: 

import  io.restassured.RestAssured.*;

public static void main(String[] args) {

// Define base URI

String baseURI = "https://api.example.com";


// Perform GET request

RestAssured.

given()

.get(baseURI+"/fact")

.then()

.statusCode(200)

.log().all(); // Log response

}

}


Question: How do you validate response status codes in RestAssured?
Answer: You can validate response status codes using the statusCode() method.


    public static void main(String[] args) {
        String baseURI = "https://api.example.com";

        RestAssured.

given()

.get(baseURI+"/fact")

.then()

.statusCode(200) // Validates if the response status code is 200

    }


Question: How do you validate response body content in RestAssured?
Answer: You can validate response body content using various methods like body(), jsonPath()


    @Test
public void testApi() {
        baseURI = "https://api.example.com";
        
        // Perform GET request

RestAssured.

given()

.get(baseURI)

.then() .log().all()

.assertThat().statusCode(200)

.body("gender", Matchers.equalTo("Value"));

// Validates if the response body contains a specific key-value pair

        
    }



Question: How do you handle authentication in RestAssured?
Answer: RestAssured provides several methods for handling authentication, including basic authentication, OAuth, and JWT authentication.

@Test

public void authApi() {

baseURI = "https://api.example.com";


RestAssured.

given()

.auth().basic("username", "password")

.get("/resource")

.then()

.statusCode(200);

}



Question: How do you send POST requests with request parameters using RestAssured?
Answer: You can send POST requests with request parameters using the formParams() method.


@Test

public void authApi() {

baseURI = "https://api.example.com";


RestAssured

.given()

.formParams("param1", "value1", "param2", "value2")

.post("/resource")

.then()

.statusCode(200);

}



Question: How do you handle response headers in RestAssured?
Answer: You can access and validate response headers using the header() method.

public void testApi() {

baseURI = "https://api.example.com";


RestAssured

.given()

.get("/resource")

.then()

.header("Content-Type", "application/json") // Validates the Content-Type header

.header("Server", "Apache"); // Validates the Server header

}

}


Question: How do you handle JSON response bodies in RestAssured?
Answer: RestAssured provides the jsonPath() method for parsing and extracting values from JSON response bodies.

@Test

public void testApi() {

String baseURi = "https://api.example.com";


String response = RestAssured.given()

.get(baseURi+"/resource")

.then()

.extract().response().asString();


String value = JsonPath.from(response).getString("key");

System.out.println("Value of key: " + value);

}



Question: How do you handle error responses in RestAssured?
Answer: You can handle error responses using the expect() method to specify expected error codes and messages.


@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured.given()

.get(baseURI+"/nonexistent-resource")

.then().log().all()

.statusCode(404)

.statusLine("HTTP/1.1 404 Not Found")

.body("message", Matchers.equalTo("Not Found"));

}


Question: How do you handle dynamic data in RestAssured tests?
Answer: RestAssured provides several mechanisms for handling dynamic data in tests, such as using path parameters, query parameters, or extracting values from response bodies and using them in subsequent requests. Here's an example of extracting a value from a response and using it in a subsequent request:


@Test

public void testApi() {

String baseURI = "https://api.example.com";


// Extracting value from response

String userId = RestAssured.given()

.get(baseURI+"/users")

.then()

.extract().path("id[0]");


// Using extracted value in subsequent request

RestAssured.given()

.pathParam("userId", userId)

.get("/users/{userId}/profile")

.then()

.statusCode(200);

}



Question: How do you handle file uploads in RestAssured?
Answer: RestAssured provides the multiPart() method for uploading files as part of a multipart request.
import static io.restassured.RestAssured.*;
import java.io.File;

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured.given()

.multiPart(new File("path/to/file.txt"))

.post(baseURI+"/upload")

.then()

.statusCode(200);

}


Question: How do you handle cookies in RestAssured?
Answer: RestAssured provides the cookie() method for handling cookies in requests and responses. 

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured. given()

.cookie("sessionId", "123456789")

.get(baseURI+"/resource")

.then()

.statusCode(200)

.cookie("sessionExpires", "2024-02-14");

}



Question: How do you handle timeouts in RestAssured?
Answer: RestAssured allows you to specify connection and request timeouts using the config() method. 

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured.given()

.config(RestAssured.config()

.httpClient(HttpClientConfig.httpClientConfig()

.setParam("http.connection.timeout", 5000)

.setParam("http.socket.timeout", 5000)))

.get("/resource")

.then()

.statusCode(200);

}



Question: How do you handle SSL certificates in RestAssured?
Answer: 
RestAssured supports handling SSL certificates using the relaxedHTTPSValidation() method to disable SSL certificate validation. 

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured. given()

.relaxedHTTPSValidation()

.get("/resource")

.then()

.statusCode(200);

}


Question: How do you handle invalid input data in RestAssured tests?
Answer:  RestAssured allows you to simulate sending invalid input data by manipulating request parameters or body content. 
Here's an example of sending an invalid JSON payload:

@Test

public void testApi() {

String baseURI = "https://api.example.com";


RestAssured.given()

.body("{ invalid: json }")

.post("/resource")

.then()

.statusCode(400);

// Assuming 400 Bad Request is expected for invalid input

}



API testing MCQ

Question : What does API stand for?

Application Programming Interface

Application Protocol Integration

Application Program Interface

Advanced Protocol Integration

Correct Answer :Application Programming Interface


Question : Which HTTP method is used to retrieve data from the server?

POST

GET

DELETE

PUT

Correct Answer :GET


Question : What HTTP status code indicates a successful API request?

200

400

500

201

Correct Answer :200


Question : Which type of API does not require constant internet connectivity?

SOAP API

RESTful API

GraphQL API

WebSocket API

Correct Answer :SOAP API


Question : In API testing, what is the purpose of a ''mock server''?

To simulate the behavior of an actual server

To secure the API from unauthorized access

To store API documentation

To optimize API performance

Correct Answer :To simulate the behavior of an actual server


Question : Which format is commonly used for data exchange in RESTful APIs?

JSON

XML

HTML

YAML

Correct Answer :JSON


Question : Which authentication method allows sending credentials with each API request?

OAuth

JWT

Basic Authentication

Digest Authentication

Correct Answer :Basic Authentication


Question : What is the role of the ''Authorization'' header in an API request?

To specify the API version

To define the request type (GET, POST, etc.)

To pass authentication credentials

To set the response format (JSON, XML, etc.)

Correct Answer :To pass authentication credentials


Question : Which testing type focuses on the flow of data between different APIs?

Integration testing

Unit testing

Functional testing

Performance testing

Correct Answer :Integration testing


Question : What does CORS stand for in the context of API testing?

Cross-Origin Resource Sharing

Cross-Origin Request Security

Centralized Origin Resource Sharing

Centralized Origin Request Security

Correct Answer :Cross-Origin Resource Sharing


Question : Which tool can be used to capture and inspect API requests and responses?

Postman

Selenium

Jira

Jenkins

Correct Answer :Postman


Question : What is the purpose of load testing in API testing?

To identify security vulnerabilities

To check API documentation accuracy

To assess API performance under varying loads

To verify API functionalities in different environments

Correct Answer :To assess API performance under varying loads


Question : Which HTTP method is used to update data on the server?

GET

DELETE

PUT

POST

Correct Answer :PUT


Question : What does the term ''endpoint'' refer to in API testing?

The data format used for API responses

The URL where API requests are sent

The authentication token for accessing the API

The HTTP status code returned by the API

Correct Answer :The URL where API requests are sent


Question : Which API testing method is used to test the functionality of individual API components?

Black-box testing

White-box testing

Grey-box testing

Alpha testing

Correct Answer :Black-box testing


Question : What is the purpose of API documentation?

To showcase API security measures

To provide a comprehensive list of API consumers

To explain how to use the API and its endpoints

To highlight API performance metrics

Correct Answer :To explain how to use the API and its endpoints


Question : Which testing approach involves running a set of tests repeatedly to find defects?

Agile testing

Ad-hoc testing

Regression testing

Exploratory testing

Correct Answer :Regression testing


Question : Which HTTP status code indicates that the requested resource is not found?

404

200

500

201

Correct Answer :404


Question : What is the purpose of API versioning?

To improve API security

To support backward compatibility

To reduce API response time

To enable API caching

Correct Answer :To support backward compatibility


Question : In API testing, what is the primary focus of security testing?

Validating API functionality

Verifying data integrity

Identifying potential vulnerabilities and threats

Assessing API scalability

Correct Answer :Identifying potential vulnerabilities and threats


Question : Which type of API testing validates the interaction between multiple integrated APIs?

Unit testing

Integration testing

Regression testing

System testing

Correct Answer :Integration testing


Question : Which tool can be used to automate API tests?

JUnit

Cucumber

JIRA

Jenkins

Correct Answer :JUnit


Question : What is the purpose of stress testing in API testing?

To measure API performance under normal conditions

To assess API response time in a controlled environment

To evaluate API behavior under high loads and beyond capacity

To verify API functionalities in different operating systems

Correct Answer :To evaluate API behavior under high loads and beyond capacity


Question : Which type of API testing is performed during the early stages of development?

Regression testing

Alpha testing

Acceptance testing

Unit testing

Correct Answer :Unit testing


Question : What does ''HTTP'' stand for in API testing?

Hypertext Transfer Protocol

Hyperlink Transfer Protocol

Hypertext Transport Protocol

Hyperlink Transport Protocol

Correct Answer :Hypertext Transfer Protocol


Question : What is the primary goal of performance testing in API testing?

To find defects in the API code

To assess the security of the API

To check API functionality against business requirements

To measure API response time and throughput under varying loads

Correct Answer :To measure API response time and throughput under varying loads


Question : Which HTTP status code indicates a server error?

200

400

500

201

Correct Answer :500


Question : What is the purpose of a ''sandbox environment'' in API testing?

To host the API documentation

To simulate the production environment for testing

To restrict access to specific API consumers

To enable load balancing for API requests

Correct Answer :To simulate the production environment for testing


Question : Which testing type focuses on the business requirements and user expectations of an API?

Functional testing

Security testing

Load testing

Usability testing

Correct Answer :Functional testing


Question : What is the purpose of API governance?

To manage API access permissions

To ensure the availability of API endpoints

To define guidelines and standards for API development and usage

To test API performance under varying network conditions

Correct Answer :To define guidelines and standards for API development and usage


Question : Which HTTP method is used to create new resources on the server?

GET

DELETE

PUT

POST

Correct Answer :POST


Question : What is the primary purpose of a ''bearer token'' in API authentication?

To encrypt API requests

To define the API version

To authenticate API consumers

To specify the request type (GET, POST, etc.)

Correct Answer :To authenticate API consumers


Question : Which type of API testing focuses on the API's usability and user experience?

Usability testing

Security testing

Performance testing

Regression testing

Correct Answer :Usability testing


Question : What is the purpose of boundary value analysis in API testing?

To validate API responses

To determine API response time

To identify defects related to input values at the edges of valid ranges

To optimize API request payload size

Correct Answer :To identify defects related to input values at the edges of valid ranges


Question : Which type of API testing verifies the behavior of an API across different browsers and devices?

Cross-browser testing

Performance testing

Security testing

Integration testing

Correct Answer :Cross-browser testing


Question : What is the purpose of a ''rate limit'' in API testing?

To limit the number of API requests per minute/hour/day for a specific consumer

To set the response format for API requests

To define the API version

To specify the request type (GET, POST, etc.)

Correct Answer :To limit the number of API requests per minute/hour/day for a specific consumer


Question : Which tool can be used to generate synthetic data for API testing?

Postman

Swagger

JMeter

Faker

Correct Answer :Faker


Question : What is the purpose of ''negative testing'' in API testing?

To verify the performance of API endpoints

To check the response time of API requests

To test how the API handles invalid input and error conditions

To evaluate the security measures implemented in the API

Correct Answer :To test how the API handles invalid input and error conditions


Question : Which HTTP status code indicates a successful resource creation?

200

201

400

500

Correct Answer :201


Question : What is the purpose of ''latency testing'' in API testing?

To measure API response time

To validate the correctness of API responses

To assess API security vulnerabilities

To verify API functionalities under high loads

Correct Answer :To measure API response time


Question : Which type of API testing focuses on the API's performance, scalability, and responsiveness?

Performance testing

Security testing

Usability testing

Regression testing

Correct Answer :Performance testing


Question : What is the purpose of API contract testing?

To validate API functionality

To ensure consistency between API documentation and implementation

To assess API response time under load

To optimize API request payload size

Correct Answer :To ensure consistency between API documentation and implementation


Question : Which type of API testing is used to validate the correctness of API responses?

Load testing

Performance testing

Functional testing

Usability testing

Correct Answer :Functional testing


Question : What is the purpose of an ''API key'' in API authentication?

To encrypt API requests

To define the API version

To authenticate API consumers

To specify the request type (GET, POST, etc.)

Correct Answer :To authenticate API consumers


Question : Which HTTP status code indicates a client error?

200

400

500

201

Correct Answer :400


Question : What is the primary purpose of ''regression testing'' in API testing?

To validate API functionality

To identify defects in the API code

To assess API security vulnerabilities

To ensure that new code changes do not affect existing functionalities

Correct Answer :To ensure that new code changes do not affect existing functionalities


Question : Which type of API testing is performed to check if the API meets the specified requirements?

Unit testing

Integration testing

System testing

Acceptance testing

Correct Answer :Acceptance testing


Question : What is the purpose of ''data-driven testing'' in API testing?

To validate API responses

To assess the security of the API

To test the API's functionality with multiple sets of input data

To verify the API documentation accuracy

Correct Answer :To test the API's functionality with multiple sets of input data


Question : Which tool can be used to perform load testing on APIs?

Postman

Swagger

JMeter

Cucumber

Correct Answer :JMeter


Question : What is the purpose of ''concurrency testing'' in API testing?

To measure API response time

To assess API security vulnerabilities

To verify API functionalities under varying network conditions

To evaluate the API's behavior when multiple users access it simultaneously

Correct Answer :To evaluate the API's behavior when multiple users access it simultaneously


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()



Wednesday, 16 August 2023

Privacy Policy for JavaApp

Effective Date: 16 Aug 2023

1. Introduction :  This Privacy Policy outlines how we collect, use, disclose, and safeguard your personal information when you use our Android application ("App"). By accessing or using the App, you agree to the terms and practices described in this Privacy Policy. If you do not agree with our policies and practices, please do not use the App.

2. Information We Collect : -

2.1. Personal Information: We do not collect any personal information from you directly. However, we may collect non-personal information such as device information (e.g., device type, operating system, unique device identifier), and usage data (e.g., pages visited, interactions within the App).

2.2. User-Generated Content: The App allows you to submit questions and answers. Any content you submit will be stored on your local device. 

3. How We Use Your Information -We may use non-personal information for analytical purposes, to monitor and analyze usage patterns and trends in order to improve the App's performance and user experience.

4. Sharing of Information : -

4.1. We do not sell, trade, or rent your personal information to third parties.

4.2. User-generated content may be shared within the App to provide a collaborative learning experience. This content will not be shared externally without your explicit consent, except as required by law.

5. Data Security - We implement reasonable security measures to protect your personal information from unauthorized access, alteration, disclosure, or destruction. As we are not storing/asking any personal information

    We reserve the right to modify this Privacy Policy at any time. Any changes will be effective immediately upon posting the updated Privacy Policy.

Featured

Software Testing

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

popular