Sunday, 27 August 2023

Git Commands

Question: Configure Git
Answer:
git config --global user.name "Your Name"
git config --global user.email "[your.email@example.com](mailto:your.email@example.com)"
Question: Create a new Git repository
Answer:
git init
Question: Clone a remote repository to your local machine
Answer:
git clone 
Question: Check the status of your working directory and staging area
Answer:
git status
Question: Add changes to the staging area
Answer:
git add   # To stage a specific file
git add .            # To stage all changes
Question: Commit changes to the repository with a descriptive message
Answer:
git commit -m "Your commit message here"
Question: Push changes to a remote repository
Answer:
git push origin 
Question: Pull changes from a remote repository
Answer:
git pull origin 
Question: Create a new branch
Answer:
git branch 
Question: Switch to an existing branch
Answer:
git checkout 
Question: Create a new branch and switch to it in one command
Answer:
git checkout -b 
Question: Merge changes from one branch to another
Answer:
git merge 
Question: View the commit history
Answer:
git log
Question: View the difference between the working directory and the last commit
Answer:
git diff
Question: View the difference between two branches
Answer:
git diff  
Question: Discard changes in the working directory
Answer:
git checkout -- 
Question: Discard changes in the staging area and working directory
Answer:
git reset --hard HEAD
Question: Undo the last commit and move changes to the staging area
Answer:
git reset --soft HEAD~1
Question: Create and apply a stash to save and temporarily remove changes
Answer:
git stash push -m "Your stash message"
git stash apply
Question: Fetch changes from a remote repository without merging
Answer:
git fetch
Question: Rename a file and stage the change
Answer:
git mv  
Question: Delete a branch
Answer:
git branch -d 
Question: Show the remote repositories
Answer:
git remote -v
Question: Add a remote repository
Answer:
git remote add  
Question: Change the remote repository URL
Answer:
git remote set-url  
Question: Push to a specific branch on the remote repository
Answer:
git push  :
Question: Pull changes from a remote repository and automatically merge
Answer:
git pull
Question: Create an annotated tag for a specific commit
Answer:
git tag -a  -m "Tag message" 
Question: List all tags in the repository
Answer:
git tag
Question: Show the details of a specific tag
Answer:
git show 
Question: Revert changes from a specific commit
Answer:
git revert 
Question: Change the last commit message
Answer:
git commit --amend -m "New commit message"
Question: Move the HEAD to a specific commit
Answer:
git reset 
Question: Create a new branch from a specific commit
Answer:
git branch  
Question: List all branches (local and remote)
Answer:
git branch -a
Question: Show the difference between two commits
Answer:
git diff  
Question: Show a summary of the changes introduced by a commit
Answer:
git show 
Question: Move changes from the working directory to the staging area
Answer:
git add -u
Question: Delete a file from the working directory and stage the change
Answer:
git rm 
Question: Create an empty commit (useful for triggering hooks)
Answer:
git commit --allow-empty -m "Empty commit"
Question: Show the configuration settings
Answer:
git config --list
Question: Edit the Git configuration file
Answer:
git config --global --edit
Question: Show the Git version
Answer:
git --version
Question: Show the working tree status in short format
Answer:
git status -s
Question: Show the branch name you are currently on
Answer:
git rev-parse --abbrev-ref HEAD
Question: Show the changes made in the last commit
Answer:
git show HEAD
Question: Rename a branch
Answer:
git branch -m  
Question: Remove files from the staging area but keep the changes in the working directory
Answer:
git reset 
Question: Remove files from the staging area but keep them in the working directory
Answer:
git rm --cached 
Question: Undo the last commit and keep the changes in the working directory
Answer:
git reset HEAD~1
Question: How to Resolve Merge Conflicts in Git
Answer: Step 1: The easiest way to resolve a conflicted file is to open it and make the necessary changes.

Step 2: After editing the file, use the git add command to stage the resolved content.

Step 3: The final step is to create a new commit with the git commit command.

Step 4: Git creates a merge commit to finalize the merge when a merge requires a merge commit.

Git Commands to Resolve Conflicts:

1. git log --merge
The git log --merge command helps identify commits that are relevant to the merge conflict.

2. git diff
The git diff command helps identify differences between repository states or files.

3. git checkout
The git checkout command can be used to restore changes to files or switch branches.

4. git reset --mixed
The git reset --mixed command resets the staging area while keeping changes in the working directory.

5. git merge --abort
The git merge --abort command exits the merge process and attempts to restore the state before the merge began.

6. git reset
The git reset command can be used during a merge conflict to reset the index and move the current branch to another state, depending on the specified options.

Git MCQ

Question : What is Git?

A version control system

A programming language

An operating system

A web browser

Correct Answer :  A version control system 

 

Question : How do you create a new Git repository?

`git init`

`git create`

`git new`

`git repo init`

Correct Answer :  `git init` 

 

Question : How do you clone an existing Git repository?

`git clone <repository_url>`

`git pull <repository_url>`

`git checkout <repository_url>`

`git fetch <repository_url>`

Correct Answer :  `git clone <repository_url>` 

 

Question : How do you stage changes in Git?

`git add .`

`git commit -m 'message'`

`git stage .`

`git push`

Correct Answer :  `git add .` 

 

Question : How do you commit changes in Git?

`git commit -m 'message'`

`git add .`

`git push`

`git commit -a -m 'message'`

Correct Answer :  `git commit -m 'message'` 

 

Question : How do you check the status of your Git repository?

`git status`

`git info`

`git check`

`git show`

Correct Answer :  `git status` 

 

Question : How do you create a new branch in Git?

`git new-branch <branch_name>`

`git create-branch <branch_name>`

`git branch <branch_name>`

`git checkout -b <branch_name>`

Correct Answer :  `git checkout -b <branch_name>` 

 

Question : How do you switch to a different branch in Git?

`git switch <branch_name>`

`git checkout <branch_name>`

`git change-branch <branch_name>`

`git move-to <branch_name>`

Correct Answer :  `git checkout <branch_name>` 

 

Question : How do you merge branches in Git?

`git merge <branch_name>`

`git branch <branch_name>`

`git merge-branch <branch_name>`

`git combine <branch_name>`

Correct Answer :  `git merge <branch_name>` 

 

Question : How do you resolve conflicts in Git?

Manually edit the conflicted files

`git resolve`

`git conflict`

`git fix`

Correct Answer :  Manually edit the conflicted files 

 

Question : How do you view the commit history in Git?

`git log`

`git history`

`git show`

`git commits`

Correct Answer :  `git log` 

 

Question : How do you discard changes in a file and revert to the last commit version in Git?

`git discard <file>`

`git revert <file>`

`git reset <file>`

`git remove <file>`

Correct Answer :  `git reset <file>` 

 

Question : How do you remove a file from a Git repository?

`git remove <file>`

`git delete <file>`

`git rm <file>`

`git erase <file>`

Correct Answer :  `git rm <file>` 

 

Question : How do you rename a file in Git?

`git rename <old_name> <new_name>`

`git mv <old_name> <new_name>`

`git move <old_name> <new_name>`

`git rename-file <old_name> <new_name>`

Correct Answer :  `git mv <old_name> <new_name>` 

 

Question : How do you view the changes made in a specific commit in Git?

`git changes <commit_id>`

`git show <commit_id>`

`git diff <commit_id>`

`git view <commit_id>`

Correct Answer :  `git show <commit_id>` 

 

Question : How do you remove untracked files in Git?

`git remove-untracked`

`git clean`

`git clear`

`git remove --untracked`

Correct Answer :  `git clean` 

 

Question : How do you undo the last commit in Git?

`git undo`

`git revert HEAD`

`git reset --hard HEAD`

`git commit --undo`

Correct Answer :  `git reset --hard HEAD` 

 

Question : How do you create and apply a Git patch?

`git create-patch` and `git apply-patch`

`git patch-create` and `git patch-apply`

`git diff > patch` and `git apply patch`

`git create-diff` and `git apply-diff`

Correct Answer :  `git diff > patch` and `git apply patch` 

 

Question : How do you discard changes in all files and revert to the last commit version in Git?

`git discard-all`

`git reset --hard HEAD`

`git revert-all`

`git remove-all`

Correct Answer :  `git reset --hard HEAD` 

 

Question : How do you remove a branch in Git?

`git remove-branch <branch_name>`

`git branch -d <branch_name>`

`git delete <branch_name>`

`git rm <branch_name>`

Correct Answer :  `git branch -d <branch_name>` 

 

Question : How do you rename a branch in Git?

`git rename-branch <old_name> <new_name>`

`git mv-branch <old_name> <new_name>`

`git branch -m <old_name> <new_name>`

`git move-branch <old_name> <new_name>`

Correct Answer :  `git branch -m <old_name> <new_name>` 

 

Question : How do you view the changes made between two commits in Git?

`git diff <commit1> <commit2>`

`git changes <commit1>..<commit2>`

`git show <commit1>..<commit2>`

`git diff <commit1>..<commit2>`

Correct Answer :  `git diff <commit1> <commit2>` 

 

Question : How do you create an empty commit in Git?

`git commit --empty`

`git commit -e`

`git commit -a`

`git commit --allow-empty`

Correct Answer :  `git commit --allow-empty` 

 

Question : How do you remove a remote branch in Git?

`git remote remove <branch_name>`

`git remove remote <branch_name>`

`git remote delete <branch_name>`

`git push --delete origin <branch_name>`

Correct Answer :  `git push --delete origin <branch_name>` 

 

Question : How do you update your local repository with changes from the remote repository in Git?

`git fetch` followed by `git merge`

`git pull`

`git sync`

`git update`

Correct Answer :  `git pull` 

 

Question : How do you view the list of remote repositories in Git?

`git list-remotes`

`git remote show`

`git remote list`

`git remote -v`

Correct Answer :  `git remote -v` 

 

Question : How do you push a new branch to a remote repository in Git?

`git push <remote> <branch>`

`git push --branch <branch>`

`git push origin <branch>`

`git push -b <branch>`

Correct Answer :  `git push <remote> <branch>` 

 

Question : How do you configure your name and email in Git?

`git set-name <name>` and `git set-email <email>`

`git config user.name <name>` and `git config user.email <email>`

`git name <name>` and `git email <email>`

`git config --name <name>` and `git config --email <email>`

Correct Answer :  `git config user.name <name>` and `git config user.email <email>` 

 

Question : How do you create an annotated tag in Git?

`git tag <tag_name>`

`git create-tag <tag_name>`

`git annotate-tag <tag_name>`

`git tag -a <tag_name>`

Correct Answer :  `git tag -a <tag_name>` 

 

Question : How do you view the list of tags in Git?

`git list-tags`

`git show-tags`

`git tag`

`git tag list`

Correct Answer :  `git tag`

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}/configurations/{id} Update configuration for user
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:

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

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

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.

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 for Simple Object Access Protocol. REST stands for Representational State Transfer.

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

3. SOAP messages use XML for their message format. REST permits different data formats such as plain text, HTML, XML, and JSON. JSON is the most commonly preferred format for transferring data in many REST APIs. Question: How do you handle error handling and exception testing in API testing?
Answer: Handling error 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, such as 400 for Bad Request or 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., OAuth 2.0):
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 OAuth 2.0 or other 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 OAuth 2.0 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.

Best Practices for Authentication Testing:

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 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 or submit data), PUT (replace 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, such as page number or page size. Question: HTTP Request Methods
Answer: GET
GET retrieves a representation of a resource from the server. It is commonly used to retrieve data and does not typically contain a request body. For example, when a browser requests a web page, it commonly sends a GET request to retrieve the page contents.

POST
POST is used to submit data to the server for processing. It is commonly used to create resources or trigger operations, and the data is typically included in the request body.

PUT
PUT is used to replace the current representation of a resource with the representation provided in the request. It is commonly used when the client wants to replace an existing entity completely.

PATCH
PATCH is used to apply partial modifications to a resource. The request body generally contains the changes or information needed to modify the resource rather than a complete replacement representation.

HEAD
HEAD is similar to GET, but the server returns the response headers without the response body. It can be used to check metadata such as a resource's size or modification information without downloading the response body.

DELETE
DELETE requests that the server remove the specified resource. A DELETE request commonly does not contain a request body, although HTTP does not universally prohibit a body on DELETE requests.

OPTIONS
OPTIONS requests information about the communication options available for a target resource. It can be used to determine which HTTP methods and other options are supported by the server. It is also commonly involved in CORS preflight requests.
Question: What is Latency in API testing?
Answer: Latency refers to the delay involved in processing an API request and receiving a response. It can include network communication and server processing time. Lower latency generally results in better application responsiveness and performance. Question: Key components of ReadyAPI and how they contribute to API testing
Answer: ReadyAPI is a comprehensive API testing tool that offers various 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 artifacts related to API testing. It allows you to organize 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 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 such as 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, such as development, staging, and 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 such as 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 test results, including pass/fail status, response data, and logs. Reports are useful for tracking the health of APIs and debugging issues.

10. Integration: ReadyAPI 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, helping ensure the reliability and quality of web services. Question: HTTP Response Status Codes
Answer: 1xx — Informational
Informational responses indicate that the request was received and the process is continuing.

100 — Continue: The server has received the initial part of the request and indicates that the client may continue sending the request.

101 — Switching Protocols: The server is switching protocols as requested by the client.

102 — Processing: The server has received and is processing the request, but no response is available yet.

103 — Early Hints: The response can be used with the Link header to allow a user agent to preload resources while the server prepares the final response.

2xx — Success
Successful responses indicate that the request was successfully received, understood, and processed or accepted.

200 — OK: The request succeeded.

201 — Created: The request succeeded and a new resource was created as a result. This is commonly returned after POST requests and can also be returned after some PUT requests.

202 — Accepted: The request has been accepted for processing, but processing has not necessarily been completed.

203 — Non-Authoritative Information: The request was successful, but the returned metadata or representation may have been modified or obtained from a transforming proxy rather than directly from the origin server.

204 — No Content: The request succeeded, but there is no response content in the response body.

205 — Reset Content: The request succeeded, and the user agent should reset the document view or input used for the request.

206 — Partial Content: The server is delivering part of the resource, as requested by the Range header.

207 — Multi-Status: The response provides information about multiple resources or operations, with individual status information for each.

3xx — Redirection
Redirection responses indicate that further action may be needed to complete the request.

300 — Multiple Choices: The request has multiple possible representations or responses, from which the user agent may choose.

301 — Moved Permanently: The requested resource has been permanently moved to another URL or URI.

302 — Found: The requested resource is temporarily available at another URL or URI.

303 — See Other: The client should retrieve the requested resource using another URL, typically with a GET request.

305 — Use Proxy: This status code indicates that the requested resource must be accessed through the proxy specified by the response. It is deprecated and should not be used by modern applications.

307 — Temporary Redirect: The requested resource is temporarily available at another URL or URI, and the client should preserve the original request method when following the redirect.

308 — Permanent Redirect: The resource has permanently moved to another URI, and the client should preserve the original request method when following the redirect.

4xx — Client Error
Client error responses indicate that the request contains invalid information or cannot be fulfilled because of a client-side issue.

400 — Bad Request: The server cannot process the request because it is malformed or contains invalid information.

401 — Unauthorized: The request lacks valid authentication credentials or authentication failed.

403 — Forbidden: The server understood the request but refuses to authorize it.

404 — Not Found: The server cannot find the requested resource.

405 — Method Not Allowed: The HTTP method used in the request is not allowed for the requested resource.

407 — Proxy Authentication Required: The client must authenticate with the proxy before the request can be completed.

408 — Request Timeout: The server did not receive a complete request within the time it was prepared to wait.

409 — Conflict: The request could not be completed because it conflicts with the current state of the target resource.

411 — Length Required: The server refuses to accept the request without a defined Content-Length header.

415 — Unsupported Media Type: The server refuses to process the request because the request payload format is not supported.

417 — Expectation Failed: The expectation specified in the Expect request header cannot be met by the server.

421 — Misdirected Request: The request was directed to a server that is unable to produce a response for the target request.

423 — Locked: The target resource is locked.

429 — Too Many Requests: The client has sent too many requests within a given amount of time.

5xx — Server Error
Server error responses indicate that the server encountered an error or is unable to fulfill an apparently valid request.

500 — Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.

501 — Not Implemented: The server does not support the functionality required to fulfill the request.

502 — Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from an upstream server.

503 — Service Unavailable: The server is currently unable to handle the request, commonly because of temporary overload or maintenance.

504 — Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server.

505 — HTTP Version Not Supported: The server does not support the HTTP protocol version used in the request.

507 — Insufficient Storage: The server is unable to store the representation needed to successfully complete the request.

511 — Network Authentication Required: The client needs to authenticate to gain network access. Question: Explain Rest Assured API testing in Java
Answer: REST Assured is a Java library that provides a domain-specific language (DSL) for testing RESTful APIs. It simplifies writing and validating API tests by offering a fluent and expressive syntax. REST Assured allows you to perform HTTP operations such as GET, POST, PUT, DELETE, and PATCH, and validate responses against expected values using assertions.

Dependency:

io.rest-assured
rest-assured
6.0.1
test

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()
        .statusCode(200)
        .body("userId", equalTo(1))
        .body("id", equalTo(1));
}

}
Question: Various methods in Rest Assured API testing in Java
Answer: 1. Setting Up Base URI and Base Path:
baseURI(String uri): Sets the base URI for requests.
basePath(String path): Sets the base path for requests.

2. Request Specification:
given(): Starts building the request specification.
given().config(RestAssured.config()): Configures the request specification using a 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 using Hamcrest matchers. In REST Assured tests, response assertions are commonly performed through then().body() and related response validation methods.

6. Logging:
log().all(): Logs request and response details.
log().ifValidationFails(): Logs request and response details when validation fails.
log().ifError(): Logs request and response details when an error response is received.

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 a 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 cookies): Adds multiple cookies to the request.

10. Filters:
filter(Filter filter): Adds a filter to the request.

11. Error Handling:
REST Assured does not provide a when().error() method. Error responses can be validated using response status-code assertions and logged using methods such as log().ifError(). Exceptions thrown during request execution can be handled using standard Java exception-handling mechanisms such as try-catch.
Question: How do you log request and response details in Rest Assured?
Answer: You can log request and response details in Rest Assured using methods such as log().all(), log().ifValidationFails(), and log().ifError().

log().all(): Logs all available request or response details.
log().ifValidationFails(): Logs details when response validation fails.
log().ifError(): Logs details when an error response is received. Question: What is Rest Assured?
Answer: Rest Assured is a Java library that provides a domain-specific language (DSL) for writing powerful and maintainable tests for RESTful APIs. It simplifies the process of testing RESTful web services and supports HTTP methods such as GET, POST, PUT, DELETE, and PATCH. Question: How do you add Rest Assured to your Java project?
Answer: You can add Rest Assured to your Java project by including the dependency in your pom.xml file when using Maven or in the build.gradle file when using Gradle. The following example uses Rest Assured version 6.0.1 for Maven:


io.rest-assured
rest-assured
6.0.1
test
Question: How do you perform a simple GET request using Rest Assured?
Answer: You can perform a GET request using the given(), get(), and then() methods.

import static io.restassured.RestAssured.*;

public class ApiTest {

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

    given()
        .get(baseURI + "/fact")
    .then()
        .statusCode(200)
        .log().all();
}

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

import static io.restassured.RestAssured.*;

public class ApiTest {

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

    given()
        .get(baseURI + "/fact")
    .then()
        .statusCode(200);
}

}
Question: How do you validate response body content in Rest Assured?
Answer: You can validate response body content using methods such as body() and jsonPath(). For example:

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .get(baseURI)
    .then()
        .log().all()
        .statusCode(200)
        .body("gender", equalTo("Value"));
}

}
Question: How do you handle authentication in Rest Assured?
Answer: Rest Assured provides several methods for handling authentication, including basic authentication, OAuth, and JWT-based authentication.

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

@Test
public void authApi() {
    String baseURI = "https://api.example.com";

    given()
        .auth().basic("username", "password")
        .get(baseURI + "/resource")
    .then()
        .statusCode(200);
}

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

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

@Test
public void authApi() {
    String baseURI = "https://api.example.com";

    given()
        .formParams("param1", "value1", "param2", "value2")
        .post(baseURI + "/resource")
    .then()
        .statusCode(200);
}

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

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .get(baseURI + "/resource")
    .then()
        .header("Content-Type", "application/json")
        .header("Server", "Apache");
}

}
Question: How do you handle JSON response bodies in Rest Assured?
Answer: Rest Assured provides the jsonPath() method for parsing and extracting values from JSON response bodies. You can also extract the response and use JsonPath to retrieve specific values.

import static io.restassured.RestAssured.*;

import io.restassured.path.json.JsonPath;
import org.testng.annotations.Test;

public class ApiTest {

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

    String response = 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 Rest Assured?
Answer: You can handle error responses by validating the expected HTTP status code and response body using then() assertions. The expect() method is not required for this purpose.

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .get(baseURI + "/nonexistent-resource")
    .then()
        .log().all()
        .statusCode(404)
        .body("message", equalTo("Not Found"));
}

}
Question: How do you handle dynamic data in Rest Assured tests?
Answer: Rest Assured provides several mechanisms for handling dynamic data in tests, such as path parameters, query parameters, and extracting values from response bodies and using them in subsequent requests. The following example assumes that the API returns an id field in the first element of the users response.

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    String userId = given()
        .get(baseURI + "/users")
    .then()
        .extract()
        .path("id[0]");

    given()
        .pathParam("userId", userId)
        .get(baseURI + "/users/{userId}/profile")
    .then()
        .statusCode(200);
}

}
Question: How do you handle file uploads in Rest Assured?
Answer: Rest Assured provides the multiPart() method for uploading files as part of a multipart request.

import static io.restassured.RestAssured.*;

import java.io.File;
import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .multiPart(new File("path/to/file.txt"))
        .post(baseURI + "/upload")
    .then()
        .statusCode(200);
}

}
Question: How do you handle cookies in Rest Assured?
Answer: Rest Assured provides the cookie() method for sending cookies in requests and validating cookies in responses.

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .cookie("sessionId", "123456789")
        .get(baseURI + "/resource")
    .then()
        .statusCode(200)
        .cookie("sessionExpires", "2024-02-14");
}

}

Note: The response-cookie assertion assumes that the API actually returns a cookie named sessionExpires with the specified value. Question: How do you handle timeouts in Rest Assured?
Answer: Rest Assured allows you to configure connection and socket timeouts through its HTTP client configuration.

import static io.restassured.RestAssured.*;

import io.restassured.config.HttpClientConfig;
import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .config(config()
            .httpClient(HttpClientConfig.httpClientConfig()
                .setParam("http.connection.timeout", 5000)
                .setParam("http.socket.timeout", 5000)))
        .get(baseURI + "/resource")
    .then()
        .statusCode(200);
}

}
Question: How do you handle SSL certificates in Rest Assured?
Answer: Rest Assured supports SSL testing with the relaxedHTTPSValidation() method. This disables SSL certificate validation and can be useful in controlled testing environments where certificate validation is intentionally not required.

Important: Do not use relaxed HTTPS validation as a general production security configuration.

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .relaxedHTTPSValidation()
        .get(baseURI + "/resource")
    .then()
        .statusCode(200);
}

}
Question: How do you handle invalid input data in Rest Assured tests?
Answer: Rest Assured allows you to test invalid input data by manipulating request parameters or request body content. For example, you can intentionally send malformed JSON and verify that the API returns the expected error status code.

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

public class ApiTest {

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

    given()
        .body("{ invalid: json }")
        .post(baseURI + "/resource")
    .then()
        .statusCode(400);
}

}

Note: { invalid: json } is intentionally malformed JSON. The example assumes that the API responds with 400 Bad Request for malformed 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()



Featured

Software Testing

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

popular