Testing Tools Interview Q&A

Testing Tools Interview [Q &A ] MANUAL Testing


  1. What is Software Testing?

According to ANSI/IEEE 1059 standard – A process of analyzing a software item to detect the differences between existing and required conditions (i.e., defects) and to evaluate the features of the software item.  

  1. What are Quality Assurance and Quality Control?   

Quality Assurance: Quality Assurance involves in process-oriented activities. It ensures the prevention of defects in the process used to make Software Application. So the defects don’t arise when the Software Application is being developed.

Quality Control: Quality Control involves in product-oriented activities. It executes the program or code to identify the defects in the Software Application.

  1. What is Verification in software testing?

Verification is the process, to ensure that whether we are building the product right i.e., to verify the requirements which we have and to verify whether we are developing the product accordingly or not. Activities involved here are Inspections, Reviews, Walk-throughs. 

  1. What is Validation in software testing?

Validation is the process, whether we are building the right product i.e., to validate the product which we have developed is right or not. Activities involved in this is Testing the software application. 

  1. What is Static Testing?

Static Testing involves in reviewing the documents to identify the defects in the early stages of SDLC.

  1. What is Dynamic Testing?

Dynamic testing involves in the execution of code. It validates the output with the expected outcome.

  1. What is White Box Testing?

White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on applications internal code structure. In white-box testing, an internal perspective of the system, as well as programming skills, are used to design test cases. This testing usually was done at the unit level. 

  1. What is Black Box Testing?

Black Box Testing is a software testing method in which testers evaluate the functionality of the software under test without looking at the internal code structure. This can be applied to every level of software testing such as Unit, Integration, System and Acceptance Testing.  

  1. What is Grey Box Testing?

Grey box is the combination of both White Box and Black Box Testing. The tester who works on this type of testing needs to have access to design documents. This helps to create better test cases in this process.

  1. What is Positive and Negative Testing?

Positive Testing: It is to determine what system supposed to do. It helps to check whether the application is justifying the requirements or not.

Negative Testing: It is to determine what system not supposed to do. It helps to find the defects from the software.

  1. What is Test Strategy?

Test Strategy is a high-level document (static document) and usually developed by project manager. It is a document which captures the approach on how we go about testing the product and achieve the goals. It is normally derived from the Business Requirement Specification (BRS). Documents like Test Plan are prepared by keeping this document as a base.

  1. What is Test Plan and contents available in a Test Plan?

Test plan document is a document which contains the plan for all the testing activities to be done to deliver a quality product. Test Plan document is derived from the Product Description, SRS, or Use Case documents for all future activities of the project. It is usually prepared by the Test Lead or Test Manager.

  1. Test plan identifier
  2. References
  3. Introduction
  4. Test items (functions)
  5. Software risk issues
  6. Features to be tested
  7. Features not to be tested
  8. Approach
  9. Items pass/fail criteria
  10. Suspension criteria and resolution requirements
  11. Test deliverables
  12. Remaining test tasks
  13. Environmental needs
  14. Staff and training needs
  15. Responsibility
  16. Schedule
  17. Plan risks and contingencies
  18. Approvals
  19. Glossaries
  1. What is Test Suite?

Test Suite is a collection of test cases. The test cases which are intended to test an application.

  1. What is Test Scenario?

Test Scenario gives the idea of what we have to test. Test Scenario is like a high-level test case.

  1. What is Test Case?

Test cases are the set of positive and negative executable steps of a test scenario which has a set of pre-conditions, test data, expected result, post-conditions and actual results. 

  1. What is Test Bed?

An environment configured for testing. Test bed consists of hardware, software, network configuration, an application under test, other related software.

  1. What is Test Environment?

Test Environment is the combination of hardware and software on which Test Team performs testing.

Example:

  • Application Type: Web Application
  • OS: Windows
  • Web Server: IIS
  • Web Page Design: Dot Net
  • Client Side Validation: JavaScript
  • Server Side Scripting: ASP Dot Net
  • Database: MS SQL Server
  • Browser: IE/FireFox/Chrome
  1. What is Test Data?

Test data is the data that is used by the testers to run the test cases. Whilst running the test cases, testers need to enter some input data. To do so, testers prepare test data. It can be prepared manually and also by using tools.

For example, To test a basic login functionality having a user id, password fields. We need to enter some data in the user id and password fields. So we need to collect some test data.

  1. What is Test Harness?

A test harness is the collection of software and test data configured to test a program unit by running it under varying conditions which involves monitoring the output with expected output.

  1. What is Test Closure?

Test Closure is the note prepared before test team formally completes the testing process. This note contains the total no. of test cases, total no. of test cases executed, total no. of defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected etc.,

  1. List out Test Deliverables?
  1. Test Strategy
  2. Test Plan
  3. Effort Estimation Report
  4. Test Scenarios
  5. Test Cases/Scripts
  6. Test Data
  7. Requirement Traceability Matrix (RTM)
  8. Defect Report/Bug Report
  9. Test Execution Report
  10. Graphs and Metrics
  11. Test summary report
  12. Test incident report
  13. Test closure report
  14. Release Note
  15. Installation/configuration guide
  16. User guide
  17. Test status report
  18. Weekly status report (Project manager to client)
  1. What is Unit Testing?

Unit Testing is also called as Module Testing or Component Testing. It is done to check whether the individual unit or module of the source code is working properly. It is done by the developers in developer’s environment.

  1. What is Integration Testing?

Integration Testing is the process of testing the interface between the two software units. Integration testing is done by three ways. Big Bang Approach, Top Down Approach, Bottom-Up Approach

  1. What is System Testing?

Testing the fully integrated application to evaluate the system’s compliance with its specified requirements is called System Testing AKA End to End testing. Verifying the completed system to ensure that the application works as intended or not.

  1. What is Big Bang Approach?

Combining all the modules once and verifying the functionality after completion of individual module testing.

Top down and bottom up are carried out by using dummy modules known as Stubs and Drivers. These Stubs and Drivers are used to stand-in for missing components to simulate data communication between modules.

  1. What is Top-Down Approach?

Testing takes place from top to bottom. High-level modules are tested first and then low-level modules and finally integrating the low-level modules to a high level to ensure the system is working as intended. Stubs are used as a temporary module if a module is not ready for integration testing.

  1. What is Bottom-Up Approach?

It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up. Lowest level modules are tested first and then high-level modules and finally integrating the high-level modules to a low level to ensure the system is working as intended.  Drivers are used as a temporary module for integration testing.

  1. What is End-To-End Testing?

Refer System Testing.

  1. What is Functional Testing?

In simple words, what the system actually does is functional testing. To verify that each function of the software application behaves as specified in the requirement document. Testing all the functionalities by providing appropriate input to verify whether the actual output is matching the expected output or not. It falls within the scope of black box testing and the testers need not concern about the source code of the application.

  1. What is Non-Functional Testing?

In simple words, how well the system performs is non-functionality testing. Non-functional testing refers to various aspects of the software such as performance, load, stress, scalability, security, compatibility etc., Main focus is to improve the user experience on how fast the system responds to a request.

  1. What is Acceptance Testing?

It is also known as pre-production testing.  This is done by the end users along with the testers to validate the functionality of the application. After successful acceptance testing. Formal testing conducted to determine whether an application is developed as per the requirement. It allows the customer to accept or reject the application. Types of acceptance testing are Alpha, Beta & Gamma.

  1. What is Alpha Testing?

Alpha testing is done by the in-house developers (who developed the software) and testers. Sometimes alpha testing is done by the client or outsourcing team with the presence of developers or testers.

  1. What is Beta Testing?

Beta testing is done by a limited number of end users before delivery. Usually, it is done in the client place.

  1. What is Gamma Testing?

Gamma testing is done when the software is ready for release with specified requirements. It is done at the client place. It is done directly by skipping all the in-house testing activities.

  1. What is Smoke Testing?

Smoke Testing is done to make sure if the build we received from the development team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It helps not to waste the testing time to simply testing the whole application when the key features don’t work or the key bugs have not been fixed yet.

  1. What is Sanity Testing?

Sanity Testing is done during the release phase to check for the main functionalities of the application without going deeper. It is also called as a subset of Regression testing. It is done at the “release level”. At times due to release time constraints rigorous regression testing can’t be done to the build, sanity testing does that part by checking main functionalities.

  1. What is Retesting?

To ensure that the defects which were found and posted in the earlier build were fixed or not in the current build. Say, Build 1.0 was released. Test team found some defects (Defect Id 1.0.1, 1.0.2) and posted. Build 1.1 was released, now testing the defects 1.0.1 and 1.0.2 in this build is retesting.

  1. What is Regression Testing?

Repeated testing of an already tested program, after modification, to discover any defects introduced or uncovered as a result of the changes in the software being tested or in another related or unrelated software components.

Usually, we do regression testing in the following cases:

  1. New functionalities are added to the application
  2. Change Requirement (In organizations, we call it as CR)
  3. Defect Fixing
  4. Performance Issue Fix
  5. Environment change (E.g., Updating the DB from MySQL to Oracle)
  1. What is GUI Testing?

Graphical User Interface Testing is to test the interface between the application and the end user.

  1. What is Recovery Testing?

Recovery testing is performed in order to determine how quickly the system can recover after the system crash or hardware failure. It comes under the type of non-functional testing.

  1. What is Globalization Testing?
    Globalization is a process of designing a software application so that it can be adapted to various languages and regions without any changes.
  2. What is Internationalization Testing (I18N Testing)?

Refer Globalization Testing.

  1. What is Localization Testing (L10N Testing)?

Localization is a process of adapting globalization software for a specific region or language by adding local specific components.

  1. What is Installation Testing?
    It is to check whether the application is successfully installed and it is working as expected after installation.
  2. What is Formal Testing?
    It is a process where the testers test the application by having pre-planned procedures and proper documentation.
  3. What is Risk Based Testing?

Identify the modules or functionalities which are most likely cause failures and then testing those functionalities.

  1. What is Compatibility Testing?
    It is to deploy and check whether the application is working as expected in a different combination of environmental components.
  2. What is Exploratory Testing?
    Usually, this process will be carried out by domain experts. They perform testing just by exploring the functionalities of the application without having the knowledge of the requirements.
  3. What is Monkey Testing?

Perform abnormal action on the application deliberately in order to verify the stability of the application.

  1. What is Usability Testing?

To verify whether the application is user-friendly or not and was comfortably used by an end user or not. The main focus in this testing is to check whether the end user can understand and operate the application easily or not. An application should be self-exploratory and must not require training to operate it.

Manual Testing Interview Questions – 51-75:

  1. What is Security Testing?

Security testing is a process to determine whether the system protects data and maintains functionality as intended.

  1. What is Soak Testing?

Running a system at high load for a prolonged period of time to identify the performance problems is called Soak Testing.

  1. What is Performance Testing?

This type of testing determines or validates the speed, scalability, and/or stability characteristics of the system or application under test. Performance is concerned with achieving response times, throughput, and resource-utilization levels that meet the performance objectives for the project or product.

  1. What is Load Testing?

It is to verify that the system/application can handle the expected number of transactions and to verify the system/application behavior under both normal and peak load conditions.

  1. What is Volume Testing?

It is to verify that the system/application can handle a large amount of data

  1. What is Stress Testing?

It is to verify the behavior of the system once the load increases more than its design expectations.

  1. What is Scalability Testing?

Scalability testing is a type of non-functional testing. It is to determine how the application under test scales with increasing workload.

  1. What is Concurrency Testing?

Concurrency testing means accessing the application at the same time by multiple users to ensure the stability of the system. This is mainly used to identify deadlock issues.

  1. What is Fuzz Testing?

Fuzz testing is used to identify coding errors and security loopholes in an application. By inputting massive amount of random data to the system in an attempt to make it crash to identify if anything breaks in the application.

  1. What is Adhoc Testing?

Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In Adhoc testing, testers randomly test the application without following any documents and test design techniques. This testing is primarily performed if the knowledge of testers in the application under test is very high. Testers randomly test the application without any test cases or any business requirement document.

  1. What is Interface Testing?

Interface testing is performed to evaluate whether two intended modules pass data and communicate correctly to one another.

  1. What is Reliability Testing?
    Perform testing on the application continuously for long period of time in order to verify the stability of the application
  2. What is Bucket Testing?

Bucket testing is a method to compare two versions of an application against each other to determine which one performs better.

  1. What is A/B Testing?

Refer Bucket Testing.

  1. What is Split Testing?

Refer Bucket Testing.

  1. What are the principles of Software Testing?
  1. Testing shows presence of defects
  2. Exhaustive testing is impossible
  3. Early testing
  4. Defect clustering
  5. Pesticide Paradox
  6. Testing is context depending
  7. Absence of error fallacy
  1. What is Exhaustive Testing?

Testing all the functionalities using all valid and invalid inputs and preconditions is known as Exhaustive testing.

  1. What is Early Testing?

Defects detected in early phases of SDLC are less expensive to fix. So conducting early testing reduces the cost of fixing defects.

  1. What is Defect clustering?

Defect clustering in software testing means that a small module or functionality contains most of the bugs or it has the most operational failures.

  1. What is Pesticide Paradox?

Pesticide Paradox in software testing is the process of repeating the same test cases, again and again, eventually, the same test cases will no longer find new bugs. So to overcome this Pesticide Paradox, it is necessary to review the test cases regularly and add or update them to find more defects.

  1. What is Walk Through?

A walkthrough is an informal meeting conducts to learn, gain understanding, and find defects. The author leads the meeting and clarifies the queries raised by the peers in the meeting.

  1. What is Inspection?

Inspection is a formal meeting lead by a trained moderator, certainly not by the author. The document under inspection is prepared and checked thoroughly by the reviewers before the meeting. In the inspection meeting, the defects found are logged and shared with the author for appropriate actions. Post inspection, a formal follow-up process is used to ensure a timely and corrective action.

  1. Who are all involved in an inspection meeting?

Author, Moderator, Reviewer(s), Scribe/Recorder and Manager.

  1. What is a Defect?

The variation between the actual results and expected results is known as a defect. If a developer finds an issue and corrects it by himself in the development phase then it’s called a defect. 

  1. What is a Bug?

If testers find any mismatch in the application/system in testing phase then they call it as Bug. 

  1. What is an Error?

We can’t compile or run a program due to a coding mistake in a program. If a developer unable to successfully compile or run a program then they call it as an error.  

  1. What is a Failure?

Once the product is deployed and customers find any issues then they call the product as a failure product. After release, if an end user finds an issue then that particular issue is called as a failure. 

  1. What is Bug Severity?

Bug/Defect severity can be defined as the impact of the bug on customer’s business. It can be Critical, Major or Minor. In simple words, how much effect will be there on the system because of a particular defect. 

  1. What is Bug Priority?

Defect priority can be defined as how soon the defect should be fixed. It gives the order in which a defect should be resolved. Developers decide which defect they should take up next based on the priority. It can be High, Medium or Low. Most of the times the priority status is set based on the customer requirement. 

  1. Tell some examples of Bug Severity and Bug Priority?

High Priority & High Severity: Submit button is not working on a login page and customers are unable to login to the application

Low Priority & High Severity: Crash in some functionality which is going to deliver after couple of releases

High Priority & Low Severity: Spelling mistake of a company name on the homepage

Low Priority & Low Severity: FAQ page takes a long time to load

  1. What is the difference between a Standalone application, Client-Server application and Web application?

Standalone application:

Standalone applications follow one-tier architecture. Presentation, Business, and Database layer are in one system for a single user.

Client-Server Application:

Client-server applications follow two-tier architecture. Presentation and Business layer are in a client system and Database layer on another server. It works majorly in Intranet.

Web Application:

Web server applications follow three-tier or n-tier architecture. The presentation layer is in a client system, a Business layer is in an application server and Database layer is in a Database server. It works both in Intranet and Internet.

  1. What is Bug Life Cycle?

Bug life cycle is also known as Defect life cycle. In Software Development process, the bug has a life cycle. The bug should go through the life cycle to be closed. Bug life cycle varies depends upon the tools (QC, JIRA etc.,) used and the process followed in the organization. 

  1. What is Bug Leakage?

A bug which is actually missed by the testing team while testing and the build was released to the Production. If now that bug (which was missed by the testing team) was found by the end user or customer then we call it as Bug Leakage.

  1. What is Bug Release?

Releasing the software to the Production with the known bugs then we call it as Bug Release. These known bugs should be included in the release note.

  1. What is Defect Age?

Defect age can be defined as the time interval between date of defect detection and date of defect closure.

Defect Age = Date of defect closure – Date of defect detection

Assume, a tester found a bug and reported it on 1 Jan 2016 and it was successfully fixed on 5 Jan 2016. So the defect age is 5 days.

  1. What is Error Seeding?

Error seeding is a process of adding known errors intendedly in a program to identify the rate of error detection. It helps in the process of estimating the tester skills of finding bugs and also to know the ability of the application (how well the application is working when it has errors.)

  1. What is Showstopper Defect?

A showstopper defect is a defect which won’t allow a user to move further in the application. It’s almost like a crash.

Assume that login button is not working. Even though you have a valid username and valid password, you could not move further because the login button is not functioning.

  1. What is HotFix?

A bug which needs to handle as a high priority bug and fix it immediately.

  1. What is Boundary Value Analysis?

Boundary value analysis (BVA) is based on testing the boundary values of valid and invalid partitions. The Behavior at the edge of each equivalence partition is more likely to be incorrect than the behavior within the partition, so boundaries are an area where testing is likely to yield defects. Every partition has its maximum and minimum values and these maximum and minimum values are the boundary values of a partition. A boundary value for a valid partition is a valid boundary value. Similarly, a boundary value for an invalid partition is an invalid boundary value. 

  1. What is Equivalence Class Partition?

Equivalence Partitioning is also known as Equivalence Class Partitioning. In equivalence partitioning, inputs to the software or system are divided into groups that are expected to exhibit similar behavior, so they are likely to be proposed in the same way. Hence selecting one input from each group to design the test cases. 

  1. What is Decision Table testing?

Decision Table is aka Cause-Effect Table. This test technique is appropriate for functionalities which has logical relationships between inputs (if-else logic). In Decision table technique, we deal with combinations of inputs. To identify the test cases with decision table, we consider conditions and actions. We take conditions as inputs and actions as outputs. 

  1. What is State Transition?

Using state transition testing, we pick test cases from an application where we need to test different system transitions. We can apply this when an application gives a different output for the same input, depending on what has happened in the earlier state. 

  1. What is an entry criteria?

The prerequisites that must be achieved before commencing the testing process. 

  1. What is an exit criteria?

The conditions that must be met before testing should be concluded. 

  1. What is SDLC?

Software Development Life Cycle (SDLC) aims to produce a high-quality system that meets or exceeds customer expectations, works effectively and efficiently in the current and planned information technology infrastructure, and is inexpensive to maintain and cost-effective to enhance.

  1. What are the different available models of SDLC?
  1. Waterfall
  2. Spiral
  3. V Model
  4. Prototype
  5. Agile
  1. What is STLC?

STLC (Software Testing Life Cycle) identifies what test activities to carry out and when to accomplish those test activities. Even though testing differs between Organizations, there is a testing life cycle. 

  1. What is RTM?

Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests that are needed to verify whether the requirements are fulfilled. Requirement Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.

  1. What is Test Metrics?

Software test metrics is to monitor and control process and product. It helps to drive the project towards our planned goals without deviation. Metrics answer different questions. It’s important to decide what questions you want answers to. 

  1. When to stop testing? (Or) How do you decide when you have tested enough?

There are many factors involved in the real-time projects to decide when to stop testing.

  1. Testing deadlines or release deadlines
  2. By reaching the decided pass percentage of test cases
  3. The risk in the project is under acceptable limit
  4. All the high priority bugs, blockers are fixed
  5. When acceptance criteria is met

As per ISTQB, It depends on the risks for the system being tested.

Here I am going to conclude the post “Software Testing Interview Questions”. Final words, Bookmark this post “100 Software Testing Interview Questions” for future reference. After reading this post, if you find that we missed some important questions, please comment below we would try to include those with answers.

Here I have hand-picked few posts which will help you to learn more interview related stuff:

  • Why You Choose Software Testing As A Career
  • General Interview Questions
  • Selenium Interview Questions
  • Explain Test Automation Framework
  • Test Automation Framework Interview Questions
  • TestNG Interview Questions
  • SQL Interview Questions
  • Manual Testing Interview Questions
  • Agile Interview Questions

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ISTQB Foundation level exam Sample paper – I

1    We split testing into distinct stages primarily because:
a)    Each test stage has a different purpose.
b)    It is easier to manage testing in stages.
c)    We can run different tests in different environments.
d)    The more stages we have, the better the testing.

2    Which of the following is likely to benefit most from the use of test tools providing test capture and replay facilities?
a)    Regression testing
b)    Integration testing
c)    System testing
d)    User acceptance testing

3    Which of the following statements is NOT correct?
a)    A minimal test set that achieves 100% LCSAJ coverage will also achieve 100% branch coverage.
b)    A minimal test set that achieves 100% path coverage will also achieve 100% statement coverage.
c)    A minimal test set that achieves 100% path coverage will generally detect more faults than one that achieves 100% statement coverage.
d)    A minimal test set that achieves 100% statement coverage will generally detect more faults than one that achieves 100% branch coverage.

4    Which of the following requirements is testable?
a)    The system shall be user friendly.
b)    The safety-critical parts of the system shall contain 0 faults.
c)    The response time shall be less than one second for the specified design load.
d)    The system shall be built to be portable.

5    Analise the following highly simplified procedure:

Ask: “What type of ticket do you require, single or return?”
IF the customer wants ‘return’
Ask: “What rate, Standard or Cheap-day?”
IF the customer replies ‘Cheap-day’
Say: “That will be £11:20”
ELSE
Say: “That will be £19:50”
ENDIF
ELSE
Say: “That will be £9:75”
ENDIF

Now decide the minimum number of tests that are needed to ensure that all
the questions have been asked, all combinations have occurred and all
replies given.
a)    3
b)    4
c)    5
d)    6

6    Error guessing:
a)    supplements formal test design techniques.
b)    can only be used in component, integration and system testing.
c)    is only performed in user acceptance testing.
d)    is not repeatable and should not be used.

7    Which of the following is NOT true of test coverage criteria?
a)    Test coverage criteria can be measured in terms of items exercised by a test suite.
b)    A measure of test coverage criteria is the percentage of user requirements covered.
c)    A measure of test coverage criteria is the percentage of faults found.
d)    Test coverage criteria are often used when specifying test completion criteria.

8    In prioritizing what to test, the most important objective is to:
a)    find as many faults as possible.
b)    test high risk areas.
c)    obtain good test coverage.
d)    test whatever is easiest to test.

9    Given the following sets of test management terms (v-z), and activity descriptions (1-5), which one of the following best pairs the two sets?
v – test control
w – test monitoring
x – test estimation
y – incident management
z – configuration control

1 –   calculation of required test resources
2 –   maintenance of record of test results
3 –   re-allocation of resources when tests overrun
4 –   report on deviation from test plan
5 –   tracking of anomalous test results

a)    v-3,w-2,x-1,y-5,z-4
b)    v-2,w-5,x-1,y-4,z-3
c)    v-3,w-4,x-1,y-5,z-2
d)    v-2,w-1,x-4,y-3,z-5

10    Which one of the following statements about system testing is NOT true?
a)    System tests are often performed by independent teams.
b)    Functional testing is used more than structural testing.
c)    Faults found during system tests can be very expensive to fix.
d)    End-users should be involved in system tests.

11    Which of the following is false?
a)    Incidents should always be fixed.
b)    An incident occurs when expected and actual results differ.
c)    Incidents can be analysed to assist in test process improvement.
d)    An incident can be raised against documentation.

12    Enough testing has been performed when:
a)    time runs out.
b)    the required level of confidence has been achieved.
c)    no more faults are found.
d)    the users won’t find any serious faults.

13    Which of the following is NOT true of incidents?
a)    Incident resolution is the responsibility of the author of the software under test.
b)    Incidents may be raised against user requirements.
c)    Incidents require investigation and/or correction.
d)    Incidents are raised when expected and actual results differ.

14    Which of the following is not described in a unit test standard?
a)    syntax testing
b)    equivalence partitioning
c)    stress testing
d)    modified condition/decision coverage

15    Which of the following is false?
a)    In a system two different failures may have different severities.
b)    A system is necessarily more reliable after debugging for the removal of a fault.
c)    A fault need not affect the reliability of a system.
d)    Undetected errors may lead to faults and eventually to incorrect behaviour.

16    Which one of the following statements, about capture-replay tools, is NOT correct?
a)    They are used to support multi-user testing.
b)    They are used to capture and animate user requirements.
c)    They are the most frequently purchased types of CAST tool.
d)    They capture aspects of user behavior.

17    How would you estimate the amount of re-testing likely to be required?
a)    Metrics from previous similar projects
b)    Discussions with the development team
c)    Time allocated for regression testing
d)    a & b

18    Which of the following is true of the V-model?
a)    It states that modules are tested against user requirements.
b)    It only models the testing phase.
c)    It specifies the test techniques to be used.
d)    It includes the verification of designs.

19    The oracle assumption:
a)    is that there is some existing system against which test output may be checked.
b)    is that the tester can routinely identify the correct outcome of a test.
c)    is that the tester knows everything about the software under test.
d)    is that the tests are reviewed by experienced testers.

20    Which of the following characterizes the cost of faults?
a)    They are cheapest to find in the early development phases and the most expensive to fix in the latest test phases.
b)    They are easiest to find during system testing but the most expensive to fix then.
c)    Faults are cheapest to find in the early development phases but the most expensive to fix then.
d)    Although faults are most expensive to find during early development phases, they are cheapest to fix then.

21    Which of the following should NOT normally be an objective for a test?
a)    To find faults in the software.
b)    To assess whether the software is ready for release.
c)    To demonstrate that the software doesn’t work.
d)    To prove that the software is correct.

22    Which of the following is a form of functional testing?
a)    Boundary value analysis
b)    Usability testing
c)    Performance testing
d)    Security testing

23    Which of the following would NOT normally form part of a test plan?
a)    Features to be tested
b)    Incident reports
c)    Risks
d)    Schedule

24    Which of these activities provides the biggest potential cost saving from the use of CAST?
a)    Test management
b)    Test design
c)    Test execution
d)    Test planning

25    Which of the following is NOT a white box technique?
a)    Statement testing
b)    Path testing
c)    Data flow testing
d)    State transition testing

26    Data flow analysis studies:
a)    possible communications bottlenecks in a program.
b)    the rate of change of data values as a program executes.
c)    the use of data on paths through the code.
d)    the intrinsic complexity of the code.

27    In a system designed to work out the tax to be paid:
An employee has £4000 of salary tax free. The next £1500 is taxed at 10%
The next £28000 is taxed at 22%
Any further amount is taxed at 40%
To the nearest whole pound, which of these is a valid Boundary Value Analysis test case?
a)    £1500
b)    £32001
c)    £33501
d)    £28000

28    An important benefit of code inspections is that they:
a)    enable the code to be tested before the execution environment is ready.
b)    can be performed by the person who wrote the code.
c)    can be performed by inexperienced staff.
d)    are cheap to perform.

29    Which of the following is the best source of Expected Outcomes for User Acceptance Test scripts?
a)    Actual results
b)    Program specification
c)    User requirements
d)    System specification

30    What is the main difference between a walkthrough and an inspection?
a)    An inspection is lead by the author, whilst a walkthrough is lead by a trained moderator.
b)    An inspection has a trained leader, whilst a walkthrough has no leader.
c)    Authors are not present during inspections, whilst they are during walkthroughs.
d)    A walkthrough is lead by the author, whilst an inspection is lead by a trained moderator.

31    Which one of the following describes the major benefit of verification early in the life cycle?
a)    It allows the identification of changes in user requirements.
b)    It facilitates timely set up of the test environment.
c)    It reduces defect multiplication.
d)    It allows testers to become involved early in the project.

32    Integration testing in the small:
a)    tests the individual components that have been developed.
b)    tests interactions between modules or subsystems.
c)    only uses components that form part of the live system.
d)    tests interfaces to other systems.

33    Static analysis is best described as:
a)    the analysis of batch programs.
b)    the reviewing of test plans.
c)    the analysis of program code.
d)    the use of black box testing.

34     Alpha testing is:
a)    post-release testing by end user representatives at the developer’s site.
b)    the first testing that is performed.
c)    pre-release testing by end user representatives at the developer’s site.
d)    pre-release testing by end user representatives at their sites.

35    A failure is:
a)    found in the software; the result of an error.
b)    departure from specified behavior.
c)    an incorrect step, process or data definition in a computer program.
d)    a human action that produces an incorrect result.

36    In a system designed to work out the tax to be paid:
An employee has £4000 of salary tax free. The next £1500 is taxed at 10%
The next £28000 is taxed at 22%
Any further amount is taxed at 40%
Which of these groups of numbers would fall into the same equivalence class?
a)    £4800; £14000; £28000
b)    £5200; £5500; £28000
c)    £28001; £32000; £35000
d)    £5800; £28000; £32000

37    The most important thing about early test design is that it:
a)    makes test preparation easier.
b)    means inspections are not required.
c)    can prevent fault multiplication.
d)    will find all faults.

38    Which of the following statements about reviews is true?
a)    Reviews cannot be performed on user requirements specifications.
b)    Reviews are the least effective way of testing code.
c)    Reviews are unlikely to find faults in test plans.
d)    Reviews should be performed on specifications, code, and test plans.

39    Test cases are designed during:
a)    test recording.
b)    test planning.
c)    test configuration.
d)    test specification.

40    A configuration management system would NOT normally provide:
a)    linkage of customer requirements to version numbers.
b)    facilities to compare test results with expected results.
c)    the precise differences in versions of software component source code.
d)    restricted access to the source code library.

Answers for above questions:

Question Answer
1 -  A         2-A          3- D         4- C      5 -  A         6-  A          7 - C         8     B           9     C            10   D           11   A            12   B           13   A              14   C            15   B             16   B         17   D      18   D
19   B        20   A     21   D       22   A      23   B         24   C         25   D       26   C         27   C           28   A         29   C          30   D         31   C           32   B          33   C           34   C          35   B      36   D      37   C
38   D         39   D          40   B           


ISTQB Foundation level exam Sample paper – II

1.Software testing activities should start

a. as soon as the code is written
b. during the design  stage
c. when the requirements have been formally documented
d. as soon as possible in the development life cycle

2.Faults found by users are due to:

a. Poor quality software
b. Poor software and poor testing
c. bad luck
d. insufficient time for testing

3.What is the main reason for testing software before releasing it?

a. to show that system will work after release
b. to decide when the software is of sufficient quality to release
c. to find as many bugs as possible before release
d. to give information for a risk based decision about release

4. which of the following statements is not true

a. performance testing can be done during unit testing as well as during the testing of whole system
b. The acceptance test does not necessarily include a regression test
c. Verification  activities should not involve testers (reviews, inspections etc)
d. Test environments should be as similar to production environments as possible

5. When reporting faults found to developers, testers should be:

a. as polite, constructive and helpful as possible
b. firm about insisting that a bug is not a “feature” if it should be fixed
c. diplomatic, sensitive to the way they may react to criticism
d. All of the above

6.In which order should tests be run?

a. the most important tests first
b. the most difficult tests first(to allow maximum time for fixing)
c. the easiest tests first(to give initial confidence)
d. the order they are thought of

7. The later in the development life cycle a fault is discovered, the more expensive it is to fix. why?

a. the documentation is poor, so it takes longer to find out what the software is doing.
b. wages are rising
c. the  fault has been built into more documentation,code,tests, etc
d. none of the above

8. Which is not true-The black box tester

a. should be able to understand a functional specification or requirements document
b. should be able to understand the source code.
c. is highly motivated to find faults
d. is creative to find the system’s weaknesses

9. A test design technique is

a. a process for selecting test cases
b. a process for determining expected outputs
c. a way to measure the quality of software
d. a way to measure in a test plan what has to be done

10. Testware(test cases, test dataset)

a. needs configuration management just like requirements, design and code
b. should be newly constructed for each new version of the software
c. is needed only until the software is released into production or use
d. does not need to be documented and commented, as it does not form part of the released
software system

11. An incident logging system

a only records defects
b is of limited value
c is a valuable source of project information during testing if it contains all incidents
d. should be used only by the test team.

12. Increasing the quality of the software, by better development methods, will affect the time needed for testing (the test phases) by:

a. reducing test time
b. no change
c. increasing test time
d. can’t say

13. Coverage measurement

a. is nothing to do with testing
b. is a partial measure of test thoroughness
c. branch coverage should be mandatory for all software
d. can only be applied at unit or module testing, not at system testing

14. When should you stop testing?

a. when time for testing has run out.
b. when all planned tests have been run
c. when the test completion criteria have been met
d. when no faults have been found by the tests run

15. Which of the following is true?

a. Component testing should be black box, system testing should be white box.
b. if u find a lot of bugs in testing, you should not be very confident about the quality of software
c. the fewer bugs you find,the better your testing was
d. the more tests you run, the more bugs you will find.

16. What is the important criterion in deciding what testing technique to use?

a.  how well you know a particular technique
b. the objective of the test
c. how appropriate the technique is for testing the application
d. whether there is a tool to support the technique

17. If the pseudo code below were a programming language ,how many tests are required to achieve 100% statement coverage?

1.If x=3 then
2.     Display_messageX;
3.       If y=2 then
4.          Display_messageY;
5.       Else
6.          Display_messageZ;
7.Else
8.     Display_messageZ;

a. 1
b. 2
c. 3
d. 4

18. Using the same code example as question 17,how many  tests are required to achieve 100% branch/decision coverage?

a. 1
b. 2
c. 3
d. 4

19 Which of the following is NOT a type of non-functional test?

a. State-Transition
b. Usability
c. Performance
d. Security

20. Which of the following  tools would you use to detect a memory leak?

a. State analysis
b. Coverage analysis
c. Dynamic analysis
d. Memory analysis

21. Which  of the following is NOT a standard related to testing?

a.  IEEE829
b.  IEEE610
c.  BS7925-1
d.  BS7925-2

22.which of the following is the component test standard?

a. IEEE 829
b. IEEE 610
c. BS7925-1
d. BS7925-2

23 which of the following statements are true?

a. Faults in program specifications are the most expensive to fix.
b. Faults in code are the most expensive to fix.
c. Faults in requirements are the most expensive to fix
d. Faults in designs are the most expensive to fix.

24. Which of the following is not the integration strategy?

a. Design based
b. Big-bang
c. Bottom-up
d. Top-down

25. Which of the following is a black box design technique?

a. statement testing
b. equivalence partitioning
c. error- guessing
d. usability testing

26. A program with high cyclometic complexity  is almost likely to be:

a. Large
b. Small
c. Difficult to write
d. Difficult to test

27. Which of the following is a static test?

a. code inspection
b. coverage analysis
c. usability assessment
d. installation test

28. Which of the following is the odd one out?

a. white box
b. glass box
c. structural
d. functional

29. A program validates a numeric field as follows:

values less than 10 are rejected, values between 10 and 21 are accepted, values greater than or equal to 22 are rejected

which of the following input values cover all of the equivalence partitions?

a. 10,11,21
b.   3,20,21
c.   3,10,22
d. 10,21,22

30. Using  the same specifications as question 29, which of the following covers the MOST boundary values?

a. 9,10,11,22
b. 9,10,21,22
c. 10,11,21,22
d. 10,11,20,21

Answers of all above Questions:

Question Answer
1.   d                     2.   b                      3.   d                       4.   c                       5.   d                    6.   a                         7.   c                          8.   b                  9.   a                   10.  a
11.  c                    12.  a                    13.  b                      14.  c                      15.  b                  16.  b                       17.  c                        18.  c                   19.  a                  20.  c
21.  b                   22.  d                    23.  c                      24.  a                       25.  b                 26.  d                       27.  a                        28.  d                  29.  c                   30.  b


ISTQB Foundation level exam Sample paper – III

Q1    A deviation from the specified or expected behavior that is visible to end-users is called:

a)    an error
b)    a fault
c)    a failure
d)    a defect

Q2  Regression testing should be performed:

v)    every week
w)    after the software has changed
x)    as often as possible
y)    when the environment has changed
z)    when the project manager says

a)    v & w are true, x, y & z are false
b)    w, x & y are true, v & z are false
c)    w & y are true, v, x & z are false
d)    w is true, v, x, y & z are false

Q3    IEEE 829 test plan documentation standard contains all of the following except

a)    test items
b)    test deliverables
c)    test tasks
d)    test specifications

Q4    When should testing be stopped?

a)    when all the planned tests have been run
b)    when time has run out
c)    when all faults have been fixed correctly
d)    it depends on the risks for the system being tested

Q5    Order numbers on a stock control system can range between 10000 and 99999 inclusive. Which of the following inputs might be a result of designing tests for only valid equivalence classes and valid boundaries?

a)    1000, 50000, 99999
b)    9999, 50000, 100000
c)    10000, 50000, 99999
d)    10000, 99999, 100000

Q6    Consider the following statements about early test design:

i.    early test design can prevent fault multiplication
ii.    faults found during early test design are more expensive to fix
iii.    early test design can find faults
iv.    early test design can cause changes to the requirements
v.    early test design normally takes more effort

a)    i, iii & iv are true;  ii & v are false
b)    iii & iv are true;  i, ii & v are false
c)    i, iii, iv & v are true;  ii is false
d)    i & ii are true;  iii, iv & v are false

Q7    Non-functional system testing includes:

a)    testing to see where the system does not function correctly
b)    testing quality attributes of the system including performance and usability
c)    testing a system function using only the software required for that function
d)    testing for functions that should not exist

Q8    Which of the following is NOT part of configuration management?

a)    auditing conformance to ISO 9000
b)    status accounting of configuration items
c)    identification of test versions
d)    controlled library access

Q9    Which of the following is the main purpose of the integration strategy for integration testing in the small?

a)    to ensure that all of the small modules are tested adequately
b)    to ensure that the system interfaces to other systems and networks
c)    to specify which modules to combine when, and how many at once
d)    to specify how the software should be divided into modules

Q10    What is the purpose of a test completion criterion?

a)    to know when a specific test has finished its execution
b)    to ensure that the test case specification is complete
c)    to set the criteria used in generating test inputs
d)    to determine when to stop testing

Q11    Consider the following statements:

i.    an incident may be closed without being fixed.
ii.    incidents may not be raised against documentation.
iii.    the final stage of incident tracking is fixing.
iv.    the incident record does not include information on test environments.

a)    ii is true, i, iii and iv are false
b)    i is true, ii, iii and iv are false
c)    i and iv are true, ii and iii are false
d)    i and ii are true, iii and iv are false

Q12    Given the following code, which statement is true about the minimum number of test cases required for full statement and branch coverage?

Read p
Read q
IF p+q > 100 THEN
Print “Large”
ENDIF
IF p > 50 THEN
Print “p Large”
ENDIF

a)    1 test for statement coverage, 3 for branch coverage
b)    1 test for statement coverage, 2 for branch coverage
c)    1 test for statement coverage, 1 for branch coverage
d)    2 tests for statement coverage, 2 for branch coverage

Q13    Consider the following statements:

i.    100% statement coverage guarantees 100% branch coverage.
ii.    100% branch coverage guarantees 100% statement coverage.
iii.    100% branch coverage guarantees 100% decision coverage.
iv.    100% decision coverage guarantees 100% branch coverage.
v.    100% statement coverage guarantees 100% decision coverage.

a)    ii is True;  i, iii, iv & v are False
b)    i & v are True;  ii, iii & iv are False
c)    ii & iii are True;  i, iv & v are False
d)    ii, iii & iv are True;  i & v are False

Q14    Functional system testing is:

a)    testing that the system functions with other systems
b)    testing that the components that comprise the system function together
c)    testing the end to end functionality of the system as a whole
d)    testing the system performs functions within specified response times

Q15    Incidents would not be raised against:

a)    requirements
b)    documentation
c)    test cases
d)    improvements suggested by users

Q16    Which of the following items would not come under Configuration Management?

a)    operating systems
b)    test documentation
c)    live data
d)    user requirement documents

Q17    Maintenance testing is:

a)    updating tests when the software has changed
b)    testing a released system that has been changed
c)    testing by users to ensure that the system meets a business need
d)    testing to maintain business advantage

Q18    What can static analysis NOT find?

a)    the use of a variable before it has been defined
b)    unreachable (“dead”) code
c)    memory leaks
d)    array bound violations

Q19    Which of the following techniques is NOT a black box technique?

a)    state transition testing
b)    LCSAJ
c)    syntax testing
d)    boundary value analysis

Q20    Beta testing is:

a)    performed by customers at their own site
b)    performed by customers at the software developer’s site
c)    performed by an Independent Test Team
d)    performed as early as possible in the lifecycle

Q21    Given the following types of tool, which tools would typically be used by developers, and which by an independent system test team?

i.    static analysis
ii.    performance testing
iii.    test management
iv.    dynamic analysis

a)    developers would typically use i and iv;  test team ii and iii
b)    developers would typically use i and iii;  test team ii and iv
c)    developers would typically use ii and iv;  test team i and iii
d)    developers would typically use i, iii and iv;  test team ii

Q22    The main focus of acceptance testing is:

a)    finding faults in the system
b)    ensuring that the system is acceptable to all users
c)    testing the system with other systems
d)    testing from a business perspective

Q23    Which of the following statements about component testing is FALSE?

a)    black box test design techniques all have an associated test measurement technique
b)    white box test design techniques all have an associated test measurement technique
c)    cyclomatic complexity is not a test measurement technique
d)    black box test measurement techniques all have an associated test design technique

Q24    Which of the following statements is NOT true?

a)    inspection is the most formal review process
b)    inspections should be led by a trained leader
c)    managers can perform inspections on management documents
d)    inspection is appropriate even when there are no written documents

Q25    A typical commercial test execution tool would be able to perform all of the following, EXCEPT:

a)    calculating expected outputs
b)    comparison of expected outcomes with actual outcomes
c)    recording test inputs
d)    reading test values from a data file

Q26    The difference between re-testing and regression testing is:

a)    re-testing ensures the original fault has been removed;  regression testing looks for unexpected side-effects
b)    re-testing looks for unexpected side-effects;  regression testing ensures the original fault has been removed
c)    re-testing is done after faults are fixed;  regression testing is done earlier
d)    re-testing is done by developers;  regression testing is done by independent testers

Q27    Expected results are:

a)    only important in system testing
b)    only used in component testing
c)    most useful when specified in advance
d)    derived from the code

Q28    What type of review requires formal entry and exit criteria, including metrics:

a)    walkthrough
b)    inspection
c)    management review
d)    post project review

Q29    Which of the following uses Impact Analysis most?

a)    component testing
b)    non-functional system testing
c)    user acceptance testing
d)    maintenance testing

Q30    What is NOT included in typical costs for an inspection process?

a)    setting up forms and databases
b)    analyzing metrics and improving processes
c)    writing the documents to be inspected
d)    time spent on the document outside the meeting

Q31    Which of the following is NOT a reasonable test objective:

a)    to find faults in the software
b)    to prove that the software has no faults
c)    to give confidence in the software
d)    to find performance problems

Q32    Which expression best matches the following characteristics of the review processes:

1.    led by the author
2.    undocumented
3.    no management participation
4.    led by a moderator or leader
5.    uses entry and exit criteria

s)    inspection
t)    peer review
u)    informal review
v)    walkthrough

a)    s = 4 and 5, t = 3, u = 2, v = 1
b)    s = 4, t = 3, u = 2 and 5, v = 1
c)    s = 1 and 5, t = 3, u = 2, v = 4
d)    s = 4 and 5, t = 1, u= 2, v = 3

Q33    Which of the following is NOT part of system testing?

a)    business process-based testing
b)    performance, load and stress testing
c)    usability testing
d)    top-down integration testing

Q34    Which statement about expected outcomes is FALSE?

a)    expected outcomes are defined by the software’s behaviour
b)    expected outcomes are derived from a specification, not from the code
c)    expected outcomes should be predicted before a test is run
d)    expected outcomes may include timing constraints such as response times

Q35    The standard that gives definitions of testing terms is:

a)    ISO/IEC 12207
b)    BS 7925-1
c)    ANSI/IEEE 829
d)    ANSI/IEEE 729

Q36    The cost of fixing a fault:

a)    is not important
b)    increases the later a fault is found
c)    decreases the later a fault is found
d)    can never be determined

Q37    Which of the following is NOT included in the Test Plan document of the Test Documentation Standard?

a)    what is not to be tested
b)    test environment properties
c)    quality plans
d)    schedules and deadlines

Q38    Could reviews or inspections be considered part of testing?

a)    no, because they apply to development documentation
b)    no, because they are normally applied before testing
c)    yes, because both help detect faults and improve quality
d)    yes, because testing includes all non-constructive activities

Q39    Which of the following is not part of performance testing?

a)    measuring response times
b)    recovery testing
c)    simulating many users
d)    generating many transactions

Q40     Error guessing is best used:

a)    after more formal techniques have been applied
b)    as the first approach to deriving test cases
c)    by inexperienced testers
d)    after the system has gone live

Answers to all above questions:

Question Answer
1    C                      2    C                           3    D                      4    D                         5    C                       6    A                       7    B                        8    A                         9    C                     10    D               

11    B                     12    B                      13    D                     14    C                     15    D                    16    C                    17    B                     18    C                     19    B                    20    A     

21    A                     22    D                        23    A                    24    D                      25    A                    26    A                     27    C                    28    B                      29    D                    30    C

31    B                      32    A                       33    D                      34    A                      35    B                     36    B                    37    C                    38    C                   39    B                     40    A

Selenium Interview Q&A

Selenium Interview Q&A

  1. What is Automation Testing?

Automation testing is the process of testing a software or application using an automation testing tool to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. It is required when we have huge amount of regression test cases. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

  1. What are the benefits of Automation Testing?

This is one of the common interview questions in any Automation testing job.

  1. Saves time and money. Automation testing is faster in execution.
  2. Reusability of code. Create one time and execute multiple times with less or no maintenance.
  3. Easy reporting. It generates automatic reports after test execution.
  4. Easy for compatibility testing. It enables parallel execution in the combination of different OS and browser environments.
  5. Low-cost maintenance. It is cheaper compared to manual testing in a long run.
  6. Automated testing is more reliable.
  7. Automated testing is more powerful and versatile. Automation tools allow us to integrate with Cross Browser Testing Tools, Jenkins, Github etc.,
  8. It is mostly used for regression testing. Supports execution of repeated test cases.
  9. Minimal manual intervention. Test scripts can be run unattended.
  10. Maximum coverage. It helps to increase the test coverage.
  1. What are the challenges and limitations of Selenium WebDriver?

As we all know Selenium WebDriver is a tool which automates the browser to mimic real user actions on the web. Selenium is a free open source testing tool. Some of the challenges with selenium webdriver are as follows

  1. We cannot test windows application
  2. We cannot test mobile apps
  3. Limited reporting
  4. Handling dynamic Elements
  5. Handling page load
  6. Handling pop up windows
  7. Handling captcha
  1. What type of tests have you automated?

Our main focus is to automate test cases to do Regression testing, Smoke testing, and Sanity testing. Sometimes based on the project and the test time estimation, we do focus on End to End testing.

 

  1. How many test cases you have automated per day?

It depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

  1. What is a Framework?

A framework defines a set of rules or best practices which we can follow in a systematic way to achieve the desired results. There are different types of automation frameworks and the most common ones are:

  • Data Driven Testing Framework
  • Keyword Driven Testing Framework
  • Hybrid Testing Framework

 

  1. Have you created any Framework?

If you are a beginner: You can say “No, I didn’t get a chance to create framework from the scratch. I have used the framework which is already available. My contribution is mostly in creating test cases by using the existing framework.”

If you are a beginner but have good knowledge on creating framework: You can say “Yes, I have involved in developing framework along with other automation tester in my company.”

If you are an experienced tester: You can say “I have contributed in developing framework.” or You can say “Yes, I have created framework from the scratch. There was no automation process in my previous company. I designed the framework from the scratch.”

Why WebDriver driver = new FirefoxDriver();

  1. Can you explain the Framework which you have used in your Selenium Project?

Here we have clearly explained each component of Framework.

 

  1. Why do you prefer Selenium Automation Tool?
  1. Free and open source
  2. Have large user base and helping communities
  3. Cross-browser compatibility
  4. Platform compatibility
  5. Multiple programming languages support such as Java, Perl, Phyton, Php, C# etc.,

 

  1. What is Selenium?

Selenium is an open source (free) automated testing suite to test web applications. It supports different platforms and browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).

Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation testing.

It has four components namely,

  1. Selenium IDE (Selenium Integrated Development Environment)
  2. Selenium RC (Selenium Remote Control)
  3. Selenium WebDriver
  4. Selenium Grid
  1. What is Selenium IDE?

Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

  1. What is Selenese?

Selenese is the language which is used to write test scripts in Selenium IDE.

  1. Which is the only browser that supports Selenium IDE to be used?

Firefox

  1. What is Selenium RC?

Selenium RC AKA Selenium Remote control / Selenium 1. Selenium Remote Control was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl and C#. It supports almost every browser out there.

  1. What is Selenium WebDriver?

Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.

 

  1. What is Selenium Grid?

Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.

In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.

  1. When do you use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution

  1. What are the advantages of Selenium Grid?

It allows running test cases in parallel thereby saving test execution time.

It allows multi-browser testing

It allows us to execute test cases on multi-platform

  1. What is a hub in Selenium Grid?

A hub is a server or a central point that controls the test executions on different machines.

  1. What is a node in Selenium Grid?

Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.

  1. What are the types of WebDriver APIs available in Selenium?
  • Firefox Driver
  • Gecko Driver
  • InternetExplorer Driver
  • Chrome Driver
  • HTMLUnit Driver
  • Opera Driver
  • Safari Driver
  • Android Driver
  • iPhone Driver
  • EventFiringWebDriver
  1. Which WebDriver implementation claims to be the fastest?

The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests in the browser.

 

  1. What are the Programming Languages supported by Selenium WebDiver?
  • Java
  • C#
  • Python
  • Ruby
  • Perl
  • PHP
  1. What are the Operating Systems supported by Selenium WebDriver?
  • Windows
  • Linux
  • Apple
  1. What are the Open-source Frameworks supported by Selenium WebDriver?
  • JUnit
  • TestNG

 

  1. What are the Locators available in Selenium?

In Selenium WebDriver, there are 8 different types of locators:

  1. ID
  2. ClassName
  3. Name
  4. TagName
  5. LinkText
  6. PartialLinkText
  7. XPath
  8. CSS Selector

 

  1. What is an XPath?

XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements such as textbox, button, checkbox, Image etc., in a web page.

 

  1. What is the difference between “/” and “//”

Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document.

  1. What is the difference between Absolute Path and Relative Path?

Absolute XPath starts from the root node and ends with desired descendant element’s node. It starts with top HTML node and ends with input node. It starts with a single forward slash(/) as shown below.

/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input

1 /html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input

Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the element). It starts with a double forward slash(//) as shown below.

//input[@id='email']

1 //input[@id='email']
  1. What is the difference between Assert and Verify in Selenium?

Assert: In simple words, if the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.

Verify: In simple words, there won’t be any halt in the test execution even though the verify condition is true or false.

For detailed post check the below link.

 

  1. What are Soft Assert and Hard Assert in Selenium?

Soft Assert: Soft Assert collects errors during @Test Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.

Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test

 

  1. What are the verification points available in Selenium?

In Selenium IDE, we use Selenese Verify and Assert Commands as Verification points

In Selenium WebDriver, there is no built-in features for verification points. It totally depends on our coding style. some of the Verification points are

  • To check for page title
  • To check for certain text
  • To check for certain element (text box, button, drop down, etc.)
  1. How to launch a browser using Selenium WebDriver?

WebDriver is an Interface. We create an Object of a required driver class such as FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.,

To launch Firefox Driver:

WebDriver driver = new FirefoxDriver();

Note: If you use geckodriver with Selenium, you must upgrade to Selenium 3.3. Here we have to set the property as follows

System.setProperty("webdriver.gecko.driver", "D:Selenium EnvironmentDriversgeckodriver.exe");

1 System.setProperty("webdriver.gecko.driver", "D:Selenium EnvironmentDriversgeckodriver.exe");

To launch Chrome Driver:

WebDriver driver = new ChromeDriver();

To launch Internet Explorer Driver:

WebDriver driver = new InternetExplorerDriver();

To launch Safari Driver:

WebDriver driver = new SafariDriver();

  1. Is the FirefoxDriver a Class or an Interface?

FirefoxDriver is a Java class, and it implements the WebDriver interface.

  1. What is the super interface of WebDriver?

SearchContext.

  1. Explain the line of code Webdriver driver = new FirefoxDriver(); ?

Webdriver driver = new FirefoxDriver();

1 Webdriver driver = new FirefoxDriver();

WebDriver‘ is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.

  1. We do create a reference variable ‘driver’ of type WebDriver

WebDriver driver = new FirefoxDriver(); instead of creating FirefoxDriver driver = new FirefoxDriver();

1

2

3

4

5

WebDriver driver = new FirefoxDriver();

instead of creating

FirefoxDriver driver = new FirefoxDriver();

What is the purpose of doing this way?

If we create a reference variable driver of type WebDriver then we could use the same driver variable to work with any browser of our choice such as IEDriver, SafariDriver etc.,

  1. What are the different exceptions you have faced in Selenium WebDriver?

Some of the exceptions I have faced in my current project are

  1. ElementNotVisibleException
  2. StaleElementReferenceException

Element Not visible Exception:

This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which associates with two or more element.

Stale Element Reference Exception:

A stale element reference exception is thrown in one of two cases, the first being more common than the second.

The two reasons for Stale element reference are

  1. The element has been deleted entirely.
  2. The element is no longer attached to the DOM.

We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

Some other exceptions we usually face are as follows:

  • WebDriverException
  • IllegalStateException
  • TimeoutException
  • NoAlertPresentException
  • NoSuchWindowException
  • NoSuchElementException
  1. How to Login into any site if it is showing an Authentication Pop-Up for Username and Password?

To do this we pass username and password with the URL

http://username:password@url e.g. http://myUserName:myPassword@softwaretestingmaterial.com

1

2

http://username:password@url

e.g. http://myUserName:myPassword@softwaretestingmaterial.com

  1. What are the types of waits available in Selenium WebDriver?

In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.

  • Implicit Waits
  • Explicit Waits
  • Fluent Waits
  1. What is Implicit Wait In Selenium WebDriver?

Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

 

  1. What is WebDriver Wait In Selenium WebDriver?

WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw an exception when an element is not found.

 

  1. What is Fluent Wait In Selenium WebDriver?

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

 

  1. How to input text in the text box using Selenium WebDriver?

By using sendKeys() 1. What is Automation Testing?

Automation testing is the process of testing a software or application using an automation testing tool to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. It is required when we have huge amount of regression test cases. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

2. What are the benefits of Automation Testing?

This is one of the common interview questions in any Automation testing job.

   Saves time and money. Automation testing is faster in execution.
   Reusability of code. Create one time and execute multiple times with less or no maintenance.
   Easy reporting. It generates automatic reports after test execution.
   Easy for compatibility testing. It enables parallel execution in the combination of different OS and browser environments.
   Low-cost maintenance. It is cheaper compared to manual testing in a long run.
   Automated testing is more reliable.
   Automated testing is more powerful and versatile. Automation tools allow us to integrate with Cross Browser Testing Tools, Jenkins, Github etc.,
   It is mostly used for regression testing. Supports execution of repeated test cases.
   Minimal manual intervention. Test scripts can be run unattended.
   Maximum coverage. It helps to increase the test coverage.

3. What are the challenges and limitations of Selenium WebDriver?

As we all know Selenium WebDriver is a tool which automates the browser to mimic real user actions on the web. Selenium is a free open source testing tool. Some of the challenges with selenium webdriver are as follows

   We cannot test windows application
   We cannot test mobile apps
   Limited reporting
   Handling dynamic Elements
   Handling page load
   Handling pop up windows
   Handling captcha

4. What type of tests have you automated?

Our main focus is to automate test cases to do Regression testing, Smoke testing, and Sanity testing. Sometimes based on the project and the test time estimation, we do focus on End to End testing.

   Smoke Vs Sanity Testing – Detailed Guide

5. How many test cases you have automated per day?

It depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

6. What is a Framework?

A framework defines a set of rules or best practices which we can follow in a systematic way to achieve the desired results. There are different types of automation frameworks and the most common ones are:

   Data Driven Testing Framework
   Keyword Driven Testing Framework
   Hybrid Testing Framework

Detailed Explanation: Types of Framework

7. Have you created any Framework?

If you are a beginner: You can say “No, I didn’t get a chance to create framework from the scratch. I have used the framework which is already available. My contribution is mostly in creating test cases by using the existing framework.”

If you are a beginner but have good knowledge on creating framework: You can say “Yes, I have involved in developing framework along with other automation tester in my company.”

If you are an experienced tester: You can say “I have contributed in developing framework.” or You can say “Yes, I have created framework from the scratch. There was no automation process in my previous company. I designed the framework from the scratch.”

   Why WebDriver driver = new FirefoxDriver();

8. Can you explain the Framework which you have used in your Selenium Project?

Here we have clearly explained each component of Framework. Check this post to learn more about explain automation framework to the interviewer.

9. Why do you prefer Selenium Automation Tool?

   Free and open source
   Have large user base and helping communities
   Cross-browser compatibility
   Platform compatibility
   Multiple programming languages support such as Java, Perl, Phyton, Php, C# etc.,

   Java Interview Questions for Selenium Automation Testers

10. What is Selenium?

Selenium is an open source (free) automated testing suite to test web applications. It supports different platforms and browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).

Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation testing.

It has four components namely,

   Selenium IDE (Selenium Integrated Development Environment)
   Selenium RC (Selenium Remote Control)
   Selenium WebDriver
   Selenium Grid

11. What is Selenium IDE?

Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

12. What is Selenese?

Selenese is the language which is used to write test scripts in Selenium IDE.

13. Which is the only browser that supports Selenium IDE to be used?

Firefox

14. What is Selenium RC?

Selenium RC AKA Selenium Remote control / Selenium 1. Selenium Remote Control was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl and C#. It supports almost every browser out there.

15. What is Selenium WebDriver?

Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.

Learn Selenium WebDriver Architecture

16. What is Selenium Grid?

Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.

In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.

17. When do you use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution

18. What are the advantages of Selenium Grid?

It allows running test cases in parallel thereby saving test execution time.
It allows multi-browser testing
It allows us to execute test cases on multi-platform

19. What is a hub in Selenium Grid?

A hub is a server or a central point that controls the test executions on different machines.

20. What is a node in Selenium Grid?

Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.

21. What are the types of WebDriver APIs available in Selenium?

   Firefox Driver
   Gecko Driver
   InternetExplorer Driver
   Chrome Driver
   HTMLUnit Driver
   Opera Driver
   Safari Driver
   Android Driver
   iPhone Driver
   EventFiringWebDriver

22. Which WebDriver implementation claims to be the fastest?

The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests in the browser.

   How To Do Headless Browser Testing using Selenium WebDriver

23. What are the Programming Languages supported by Selenium WebDiver?

   Java
   C#
   Python
   Ruby
   Perl
   PHP

24. What are the Operating Systems supported by Selenium WebDriver?

   Windows
   Linux
   Apple

25. What are the Open-source Frameworks supported by Selenium WebDriver?

   JUnit
   TestNG

   Read: TestNG Complete Tutorial

26. What are the Locators available in Selenium?

In Selenium WebDriver, there are 8 different types of locators:

   ID – Practical example
   ClassName – Practical example
   Name – Practical example
   TagName – Practical example
   LinkText – Practical example
   PartialLinkText – Practical example
   XPath – Practical example
   CSS Selector – Practical example

Click here to see the detailed post on Locators.

27. What is an XPath?

XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements such as textbox, button, checkbox, Image etc., in a web page.

Learn How To Write Dynamic XPath

28. What is the difference between “/” and “//”

Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document.

29. What is the difference between Absolute Path and Relative Path?

Absolute XPath starts from the root node and ends with desired descendant element’s node. It starts with top HTML node and ends with input node. It starts with a single forward slash(/) as shown below.
/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input
1
   
/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input

Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the element). It starts with a double forward slash(//) as shown below.
//input[@id='email']
1
   
//input[@id='email']

30. What is the difference between Assert and Verify in Selenium?

Assert: In simple words, if the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.

Verify: In simple words, there won’t be any halt in the test execution even though the verify condition is true or false.

For detailed post check the below link.

   Assert Vs. Verify – with Practical Examples

31. What are Soft Assert and Hard Assert in Selenium?

Soft Assert: Soft Assert collects errors during @Test Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.

Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test

   Detailed Post: Soft Assert

32. What are the verification points available in Selenium?

In Selenium IDE, we use Selenese Verify and Assert Commands as Verification points
In Selenium WebDriver, there is no built-in features for verification points. It totally depends on our coding style. some of the Verification points are

   To check for page title
   To check for certain text
   To check for certain element (text box, button, drop down, etc.)

33. How to launch a browser using Selenium WebDriver?

WebDriver is an Interface. We create an Object of a required driver class such as FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.,

To launch Firefox Driver:
WebDriver driver = new FirefoxDriver();

Note: If you use geckodriver with Selenium, you must upgrade to Selenium 3.3. Here we have to set the property as follows
System.setProperty("webdriver.gecko.driver", "D:Selenium EnvironmentDriversgeckodriver.exe");
1
   
System.setProperty("webdriver.gecko.driver", "D:Selenium EnvironmentDriversgeckodriver.exe");

To launch Chrome Driver:
WebDriver driver = new ChromeDriver();

To launch Internet Explorer Driver:
WebDriver driver = new InternetExplorerDriver();

To launch Safari Driver:
WebDriver driver = new SafariDriver();

34. Is the FirefoxDriver a Class or an Interface?

FirefoxDriver is a Java class, and it implements the WebDriver interface.

35. What is the super interface of WebDriver?

SearchContext.

36. Explain the line of code Webdriver driver = new FirefoxDriver(); ?
Webdriver driver = new FirefoxDriver();
1
   
Webdriver driver = new FirefoxDriver();

‘WebDriver‘ is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.

37. We do create a reference variable ‘driver’ of type WebDriver
WebDriver driver = new FirefoxDriver();

instead of creating

FirefoxDriver driver = new FirefoxDriver();
1
2
3
4
5
   
WebDriver driver = new FirefoxDriver();

instead of creating

FirefoxDriver driver = new FirefoxDriver();

What is the purpose of doing this way?

If we create a reference variable driver of type WebDriver then we could use the same driver variable to work with any browser of our choice such as IEDriver, SafariDriver etc.,

38. What are the different exceptions you have faced in Selenium WebDriver?

Some of the exceptions I have faced in my current project are

   ElementNotVisibleException
   StaleElementReferenceException

Element Not visible Exception:

This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which associates with two or more element.

Stale Element Reference Exception:

A stale element reference exception is thrown in one of two cases, the first being more common than the second.

The two reasons for Stale element reference are

   The element has been deleted entirely.
   The element is no longer attached to the DOM.

We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

Some other exceptions we usually face are as follows:

   WebDriverException
   IllegalStateException
   TimeoutException
   NoAlertPresentException
   NoSuchWindowException
   NoSuchElementException

39. How to Login into any site if it is showing an Authentication Pop-Up for Username and Password?

To do this we pass username and password with the URL
http://username:password@url
e.g. http://myUserName:myPassword@softwaretestingmaterial.com
1
2
   
http://username:password@url
e.g. http://myUserName:myPassword@softwaretestingmaterial.com

40. What are the types of waits available in Selenium WebDriver?

In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.

   Implicit Waits – Click to view detailed post
   Explicit Waits – Click to view detailed post
   Fluent Waits – Click to view detailed post

41. What is Implicit Wait In Selenium WebDriver?

Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Practical example

42. What is WebDriver Wait In Selenium WebDriver?

WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw an exception when an element is not found.

Practical example

43. What is Fluent Wait In Selenium WebDriver?

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

Practical example

44. How to input text in the text box using Selenium WebDriver?

By using sendKeys() method
WebDriver driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");
1
2
3
   
WebDriver driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");

45. How to input text in the text box without calling the sendKeys()?
// To initialize js object
JavascriptExecutor JS = (JavascriptExecutor)webdriver;
// To enter username
JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'");
// To enter password
JS.executeScript("document.getElementById('Pass').value='tester'");
1
2
3
4
5
6
   
// To initialize js object
JavascriptExecutor JS = (JavascriptExecutor)webdriver;
// To enter username
JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'");
// To enter password
JS.executeScript("document.getElementById('Pass').value='tester'");

   Learn JavaScriptExecutor in Selenium with Examples

46. How to clear the text in the text box using Selenium WebDriver?

By using clear() method
WebDriver driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website");
driver.findElement(By.xpath("xpath_of_element1")).clear();
1
2
3
4
   
WebDriver driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website");
driver.findElement(By.xpath("xpath_of_element1")).clear();

47. How to get a text of a web element?

By using getText() method
package softwareTestingMaterial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TestTestTest {

    @Test
    public void testmethod(){
        System.setProperty("webdriver.chrome.driver", "D:Selenium EnvironmentDriverschromedriver.exe");
         WebDriver driver = new ChromeDriver();
         driver.get("https://www.google.com");
         String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText();
         System.out.println("Text Available is :"+availableText);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
   
package softwareTestingMaterial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TestTestTest {

@Test
public void testmethod(){
System.setProperty("webdriver.chrome.driver", "D:Selenium EnvironmentDriverschromedriver.exe");
   WebDriver driver = new ChromeDriver();
   driver.get("https://www.google.com");
   String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText();
   System.out.println("Text Available is :"+availableText);
}
}

48. How to get an attribute value using Selenium WebDriver?

By using getAttribute(value);

It returns the value of the attribute passed as a parameter.

HTML:
<input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>
1
   
<input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>

Selenium Code:
String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value");
System.out.println("Available attribute value is :"+attributeValue);
Output: valueSelenium
1
2
3
   
String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value");
System.out.println("Available attribute value is :"+attributeValue);
Output: valueSelenium

49. How to click on a hyperlink using Selenium WebDriver?

We use click() method in Selenium to click on the hyperlink
driver.findElement(By.linkText(“Software Testing Material Website”)).click();
1
   
driver.findElement(By.linkText(“Software Testing Material Website”)).click();

50. How to submit a form using Selenium WebDriver?

We use “submit” method on element to submit a form
driver.findElement(By.id("form_1")).submit();
1
   
driver.findElement(By.id("form_1")).submit();

Alternatively, you can use click method on the element which does form submission

51. How to press ENTER key on text box In Selenium WebDriver?

To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.
driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);
1
   
driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);

52. How to pause a test execution for 5 seconds at a specific point?

By using java.lang.Thread.sleep(long milliseconds) method we could pause the execution for a specific time. To pause 5 seconds, we need to pass parameter as 5000 (5 seconds)
Thread.sleep(5000)
1
   
Thread.sleep(5000)

53. Is Selenium Server needed to run Selenium WebDriver Scripts?

When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium Server.

54. What happens if I run this command. driver.get(“www.softwaretestingmaterial.com”) ;

An exception is thrown. We need to pass HTTP protocol within driver.get() method.
driver.get("https://www.softwaretestingmaterial.com");
1
   
driver.get("https://www.softwaretestingmaterial.com");

55. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?

Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)

56. What is the difference between driver.get() and driver.navigate.to(“url”)?

driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded

57. Can I navigate back and forth in a browser in Selenium WebDriver?

We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to refresh a page.

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

58. What are the different types of navigation commands?

Refer above question (Can I navigate back and forth in a browser)

59. How to fetch the current page URL in Selenium?

To fetch the current page URL, we use getCurrentURL()
driver.getCurrentUrl();
1
   
driver.getCurrentUrl();

60. How can we maximize browser window in Selenium?

To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is not already maximized
driver.manage().window().maximize();
1
   
driver.manage().window().maximize();

61. How to delete cookies in Selenium?

To delete cookies we use deleteAllCookies() method
driver.manage().deleteAllCookies();
1
   
driver.manage().deleteAllCookies();

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

There are multiple ways to refresh a page in selenium

   Using driver.navigate().refresh() command as mentioned in the question 45
   Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
   Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
   Using sendKeys(Keys.F5) on any textbox on the webpage

63. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?

driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of handles of the all the pages available.

64. What is the difference between driver.close() and driver.quit() methods?

Purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still, there is a difference.

driver.close(): To close current WebDriver instance
driver.quit(): To close all the opened WebDriver instances

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

The difference between driver.findElement() and driver.findElements() commands is-

   findElement() returns a single WebElement (found first) based on the locator passed as parameter. Whereas findElements() returns a list of WebElements, all satisfying the locator value passed.
   Syntax of findElement()-
   WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
   Syntax of findElements()-
   List <WebElement> elements = element.findElements(By.id(“value”));
   Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.

66. How to find whether an element is displayed on the web page?

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

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

67. How to select a value in a dropdown?

By using Select class

WebElement mySelectElement = driver.findElement(By.name("dropdown"));
Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);
1
2
3
4
5
   
WebElement mySelectElement = driver.findElement(By.name("dropdown"));
Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);

Practical Example:

68. How to capture Screenshot in Selenium WebDriver?

Test cases may fail while executing the test scripts. While we are executing the test cases manually we just take a screenshot and place in a result repository. The same can be done by using Selenium WebDriver.

Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are

i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page

Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a screenshot of the application under test.

In Selenium 3, we may face few issues while capturing Screenshots. To overcome we use aShot utility. Click on below links to see posts related to the normal way of capturing a screenshot and capturing a screenshot using aShot utility.

Capture screenshot using Selenium WebDriver

Full Page Screenshot using aShot utility

Failed Test Cases Screenshot

69. How to mouse hover on a web element using WebDriver?

By using Actions class
WebElement ele = driver.findElement(By.xpath("xpath"));
//Create object 'action' of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).perform();
1
2
3
4
5
   
WebElement ele = driver.findElement(By.xpath("xpath"));
//Create object 'action' of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).perform();

Practical Example.

70. How can we handle web based pop-up?

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

Practical Example.

71. How can we handle windows based pop up?

Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT, Robot class etc.

72. How to handle hidden elements in Selenium WebDriver?

It is one of the most important selenium interview questions.

We can handle hidden elements by using javaScript executor
(JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");
1
   
(JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");

73. How can you find Broken Links in a page using Selenium WebDriver?

Practical Example.

74. How to find more than one web element in the list?
// To store the list
List <WebElement> eleList = driver.findElements(By.xpath("xpath"));
// To fetch the size of the list
int listSize = eleList.size();
//for loop
for (int i=0; i<listSize; i++)
{
    // Clicking on each link
    links.get(i).click();
    // Navigating back to the previous page that stores the links
    driver.navigate().back();
}
1
2
3
4
5
6
7
8
9
10
11
12
   
// To store the list
List <WebElement> eleList = driver.findElements(By.xpath("xpath"));
// To fetch the size of the list
int listSize = eleList.size();
//for loop
for (int i=0; i<listSize; i++)
{
// Clicking on each link
links.get(i).click();
// Navigating back to the previous page that stores the links
driver.navigate().back();
}

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

By using JavascriptExecutor
// To initialize the JS object.
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
// To get the site title.
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);
1
2
3
4
5
   
// To initialize the JS object.
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
// To get the site title.
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

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

In general, we click on an element using click() method in Selenium.

For example:
driver.findElement(By.id("Id Value")).click();
1
   
driver.findElement(By.id("Id Value")).click();

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.

Package:
import org.openqa.selenium.JavascriptExecutor;
1
   
import org.openqa.selenium.JavascriptExecutor;

Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);
1
2
   
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

1. To type Text in Selenium WebDriver without using sendKeys() method
2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium
11. To click on a SubMenu which is only visible on mouse hover on Menu
12. To navigate to different page using Javascript

77. How do you read test data from excels?

Test data can efficiently be read from excel using JXL or POI API. POI API has many advantages than JXL.
Click here to see a practical example of using Apache POI.

78. Is it possible to automate the captcha using Selenium?

No, It’s not possible to automate captcha and bar code reader.

79. How to handle Ajax calls in Selenium WebDriver?

Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.

AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just because the actual page is not going to refresh.

When you click on a submit button, the required information may appear on the web page without refreshing the browser. Sometimes it may load in a second and sometimes it may take longer. We have no control over loading time. The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)

Some of the methods which are available are as follows:

1. titleIs() – The expected condition waits for a page with a specific title.
wait.until(ExpectedConditions.titleIs(“Deal of the Day”));
1
   
wait.until(ExpectedConditions.titleIs(“Deal of the Day”));

2. elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
1
   
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));

3. alertIsPresent() – The expected condition waits for an alert box to appear.
wait.until(ExpectedConditions.alertIsPresent()) !=null);
1
   
wait.until(ExpectedConditions.alertIsPresent()) !=null);

4. textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.
wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));
1
   
wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));

80. List some scenarios which we cannot automate using Selenium WebDriver?

1. Bitmap comparison is not possible using Selenium WebDriver
2. Automating Captcha is not possible using Selenium WebDriver
3. We can not read bar code using Selenium WebDriver

81. What is Object Repository in Selenium WebDriver?

Object Repository is used to store element locator values in a centralized location instead of hard coding them within the scripts. We do create a property file (.properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.

82. How you build Object Repository in your project?

In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by default in an Object Repository. QTP uses this Object Repository to play back the scripts. Coming to Selenium, there is no default Object Repository concept. It doesn’t mean that there is no Object Repository in Selenium. Even though there is no default one still we could create our own. In Selenium, we call objects as locators (such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS). Object repository is a collection of objects. One of the ways to create Object Repository is to place all the locators in a separate file (i.e., properties file). But the best way is to use Page Object Model. In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular page of a web application are stored in a class.

83. What is Page Object Model in Selenium?

Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication. Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid framework etc.  A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.

84. What is Page Factory?

We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.

85. What is the difference between Page Object Model (POM) and Page Factory?

Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.

86. What are the advantages of Page Object Model Framework?

Code reusability – We could achieve code reusability by writing the code once and use it in different tests.

Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.

Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.

Readability – Improves readability due to clean separation between test code and page specific code

87. How can you use the Recovery Scenario in Selenium WebDriver?

By using “Try Catch Block” within Selenium WebDriver Java tests.
try {
    driver.get("www.SoftwareTestingMaterial.com");
}catch(Exception e){
    System.out.println(e.getMessage());
}
1
2
3
4
5
   
try {
    driver.get("www.SoftwareTestingMaterial.com");
}catch(Exception e){
    System.out.println(e.getMessage());
}

88. How to Upload a file in Selenium WebDriver?

There are two cases which are majorly used to upload a file in Selenium WebDriver such as using SendKeys Method and using AutoIT Script.

Practical Example.

89. How to Download a file in Selenium WebDriver?

By using AutoIT script, we could download a file in Selenium WebDriver.

Practical Example

90. How to run Selenium WebDriver Test from the command line?

Run Java Program using Command Prompt

Run TestNG using Command Prompt

91. How to switch between frames in Selenium?

By using the following code, we could switch between frames.
driver.switchTo().frame();
1
   
driver.switchTo().frame();

92. How to connect a Database in selenium?

As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.

We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).

Practical Example

93. How To Resize Browser Window Using Selenium WebDriver?

To resize the browser window to particular dimensions, we use ‘Dimension’ class to resize the browser window.

Practical Example

94. How To Scroll Web Page Down Or UP Using Selenium WebDriver?

JavaScript scrollBy() method scrolls the document by the specified number of pixels.

Practical Example

95. How To Perform Right Click Action (Context Click) In Selenium WebDriver?

We use Actions class in Selenium WebDriver to do Right-Click (Context Click) action.

Practical Example

96. How To Perform Double Click Action In Selenium WebDriver?

We use Actions class to do Double click action in selenium.

Practical Example

97. How To Perform Drag And Drop Action in Selenium WebDriver?

In some applications, we may face a situation to automate drag and drop an item from one location to another location. We could not achieve these using basic elements. Selenium has provided an “Actions” class to handle this kind of scenarios. We overcome this kind of scenarios such as drag and drop using Actions Class.

To achieve this, we use Actions class in Selenium WebDriver.

Practical Example

98. How To Highlight Element Using Selenium WebDriver?

By using JavascriptExecutor interface, we could highlight the specified element

Practical Example

99. Have you used any crossbrowsertesting tool to run selenium scripts on cloud?

I have used BrowserStack to run selenium tests on multiple browsers & Multiple operating systems in parallel. Earlier we have made a video on how to use BrowserStack to run selenium scripts on the cloud. Find the link in the description below.

100. What is desired capabilities?

In Selenium we use desired capabilities to handle SSL certificates in chrome browser

We need to create an instance of DesiredCapabilities
DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();

   
DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();

101. What is Continuous Integration?

Continuous Integration is abbreviated as CI. Continuous Integration is a development practice which aims to make sure the correctness of a software. After each commit, a suite of tests run automatically and test the software to ensure whether the software is running without any breaks. If any test fails, we will get immediate feedback say “build is broken”.

In simple words, continuous integration is a process of verifying the correctness of a software.

Some of the continuous integration tools are Jenkins, TeamCity, Bamboo, Travis, Circle Ci, Bitbucket.

We can schedule the test suite execution using these CI Tools.

102. How to achieve Database testing in Selenium?

As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.

Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the Database.  If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve our task. To achieve the Database connection and work on it, we need to use JDBC API Driver.

The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation script. JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming Language and the database.

Using JDBC Driver we could do the following

i. Establish a Database connection
ii. Send SQL Queries to the Database
iii. Process the results

103. How to delete Browser Cookies with Selenium Web Driver?
driver.Manage().Cookies.DeleteAllCookies();
1
   
driver.Manage().Cookies.DeleteAllCookies();

TestNG – Interview Questions:

Here we have dealt with some important TestNG interview questions. If you want to learn more interview questions related to TestNG then here you go. We have a special post on TestNG Interview Questions. Also, you could find TestNG Complete Tutorial here

104. What is TestNG?

TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration testing.

105. What are the annotations available in TestNG?

@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test

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

TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception.

Some of the common assertions supported by TestNG are

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

107. How to create and run TestNG.xml?

In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.

108. How to set test case priority in TestNG?

We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical order.
package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
    @Test(priority=0)
    public void testCase1() {  
        system.out.println("Test Case 1");
    }
    @Test(priority=1)
    public void testCase2() {    
        system.out.println("Test Case 2");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
   
package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {  
system.out.println("Test Case 1");
}
@Test(priority=1)
public void testCase2() {
system.out.println("Test Case 2");
}
}

Output:
Test Case 1
Test Case 2
1
2
   
Test Case 1
Test Case 2

109. What is Parameterized testing in TestNG?

Parameterized tests allow developers to run the same test over and over again using different values.

There are two ways to set these parameters:

   with testng.xml - Practical Example
   with Data Providers  – Practical Example

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

TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.  This gives you maximum flexibility in how you partition your tests and doesn’t require you to recompile anything if you want to run two different sets of tests back to back.

Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath.
@Test (groups = { "smokeTest", "functionalTest" })
public void loginTest(){
System.out.println("Logged in successfully");
}
1
2
3
4
   
@Test (groups = { "smokeTest", "functionalTest" })
public void loginTest(){
System.out.println("Logged in successfully");
}

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

Ans. TestNG listeners are used to configure reports and logging. One of the most widely used listeners in TestNG is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We should implement this interface creating a listener class of our own. Next, we should add the listeners annotation (@Listeners) in the Class which was created.

112. How can we create a data-driven framework using TestNG?

By using @DataProvider annotation,  we can create a Data Driven Testing Framework.
@DataProvider(name="getData")
    public Object[][] getData(){
        //Object [][] data = new Object [rowCount][colCount];
        Object [][] data = new Object [2][2];
       
        data [0][0] = "FirstUid";
        data [0][1] = "FirstPWD";
       
        data[1][0] = "SecondUid";
        data[1][1] = "SecondPWD";
       
        return data;
       
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   
@DataProvider(name="getData")
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];

data [0][0] = "FirstUid";
data [0][1] = "FirstPWD";

data[1][0] = "SecondUid";
data[1][1] = "SecondPWD";

return data;

}

Practical Example
113. Where you have applied OOPS in Automation Framework?
Check this link
114. How to handle browser (chrome) notifications in Selenium?
Notification Popup
In Chrome, we can use ChromeOptions as shown below.
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);
1
2
3
   
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

method

WebDriver driver = new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");

1

2

3

WebDriver driver = new FirefoxDriver();

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

driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");

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

// To initialize js object JavascriptExecutor JS = (JavascriptExecutor)webdriver; // To enter username JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'"); // To enter password JS.executeScript("document.getElementById('Pass').value='tester'");

1

2

3

4

5

6

// To initialize js object

JavascriptExecutor JS = (JavascriptExecutor)webdriver;

// To enter username

JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'");

// To enter password

JS.executeScript("document.getElementById('Pass').value='tester'");

 

  1. How to clear the text in the text box using Selenium WebDriver?

By using clear() method

WebDriver driver = new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website"); driver.findElement(By.xpath("xpath_of_element1")).clear();

1

2

3

4

WebDriver driver = new FirefoxDriver();

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

driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website");

driver.findElement(By.xpath("xpath_of_element1")).clear();

  1. How to get a text of a web element?

By using getText() method

package softwareTestingMaterial; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class TestTestTest {     @Test     public void testmethod(){         System.setProperty("webdriver.chrome.driver", "D:Selenium EnvironmentDriverschromedriver.exe");         WebDriver driver = new ChromeDriver();         driver.get("https://www.google.com");         String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText();         System.out.println("Text Available is :"+availableText);     } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package softwareTestingMaterial;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

public class TestTestTest {

@Test

public void testmethod(){

System.setProperty("webdriver.chrome.driver", "D:Selenium EnvironmentDriverschromedriver.exe");

  WebDriver driver = new ChromeDriver();

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

  String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText();

  System.out.println("Text Available is :"+availableText);

}

}

  1. How to get an attribute value using Selenium WebDriver?

By using getAttribute(value);

It returns the value of the attribute passed as a parameter.

HTML:

<input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>

1 <input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>

Selenium Code:

String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value"); System.out.println("Available attribute value is :"+attributeValue); Output: valueSelenium

1

2

3

String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value");

System.out.println("Available attribute value is :"+attributeValue);

Output: valueSelenium

  1. How to click on a hyperlink using Selenium WebDriver?

We use click() method in Selenium to click on the hyperlink

driver.findElement(By.linkText(“Software Testing Material Website”)).click();

1 driver.findElement(By.linkText(“Software Testing Material Website”)).click();
  1. How to submit a form using Selenium WebDriver?

We use “submit” method on element to submit a form

driver.findElement(By.id("form_1")).submit();

1 driver.findElement(By.id("form_1")).submit();

Alternatively, you can use click method on the element which does form submission

  1. How to press ENTER key on text box In Selenium WebDriver?

To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.

driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);

1 driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);
  1. How to pause a test execution for 5 seconds at a specific point?

By using java.lang.Thread.sleep(long milliseconds) method we could pause the execution for a specific time. To pause 5 seconds, we need to pass parameter as 5000 (5 seconds)

Thread.sleep(5000)

1 Thread.sleep(5000)
  1. Is Selenium Server needed to run Selenium WebDriver Scripts?

When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium Server.

  1. What happens if I run this command. driver.get(“www.softwaretestingmaterial.com”) ;

An exception is thrown. We need to pass HTTP protocol within driver.get() method.

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

1 driver.get("https://www.softwaretestingmaterial.com");
  1. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?

Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)

  1. What is the difference between driver.get() and driver.navigate.to(“url”)?

driver.get(): To open an URL and it will wait till the whole page gets loaded

driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded

  1. Can I navigate back and forth in a browser in Selenium WebDriver?

We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to refresh a page.

driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history

driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history

driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements

driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL

  1. What are the different types of navigation commands?

Refer above question (Can I navigate back and forth in a browser)

  1. How to fetch the current page URL in Selenium?

To fetch the current page URL, we use getCurrentURL()

driver.getCurrentUrl();

1 driver.getCurrentUrl();
  1. How can we maximize browser window in Selenium?

To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is not already maximized

driver.manage().window().maximize();

1 driver.manage().window().maximize();
  1. How to delete cookies in Selenium?

To delete cookies we use deleteAllCookies() method

driver.manage().deleteAllCookies();

1 driver.manage().deleteAllCookies();
  1. What are the ways to refresh a browser using Selenium WebDriver?

There are multiple ways to refresh a page in selenium

  • Using driver.navigate().refresh() command as mentioned in the question 45
  • Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
  • Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
  • Using sendKeys(Keys.F5) on any textbox on the webpage
  1. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?

driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)

driver.getWindowHandles() – It returns a set of handles of the all the pages available.

  1. What is the difference between driver.close() and driver.quit() methods?

Purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still, there is a difference.

driver.close(): To close current WebDriver instance

driver.quit(): To close all the opened WebDriver instances

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

The difference between driver.findElement() and driver.findElements() commands is-

  • findElement() returns a single WebElement (found first) based on the locator passed as parameter. Whereas findElements() returns a list of WebElements, all satisfying the locator value passed.
  • Syntax of findElement()-
    WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
    Syntax of findElements()-
    List <WebElement> elements = element.findElements(By.id(“value”));
  • Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.
  1. How to find whether an element is displayed on the web page?

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

  1. isDisplayed()
  2. boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
  1. 1
  • boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
  • isSelected()
  • boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected();
  1. 1
  • boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected();
  • isEnabled()
  • boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();
  1. 1
  • boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();
  1. How to select a value in a dropdown?

By using Select class

WebElement mySelectElement = driver.findElement(By.name("dropdown")); Select dropdown = new Select(mySelectElement); dropdown.selectByVisibleText(Text); dropdown.selectByIndex(Index); dropdown.selectByValue(Value);

1

2

3

4

5

WebElement mySelectElement = driver.findElement(By.name("dropdown"));

Select dropdown = new Select(mySelectElement);

dropdown.selectByVisibleText(Text);

dropdown.selectByIndex(Index);

dropdown.selectByValue(Value);

 

  1. How to capture Screenshot in Selenium WebDriver?

Test cases may fail while executing the test scripts. While we are executing the test cases manually we just take a screenshot and place in a result repository. The same can be done by using Selenium WebDriver.

Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are

  1. Application issues
  2. Assertion Failure

iii. Difficulty to find Webelements on the web page

  1. Timeout to find Webelements on the web page

Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a screenshot of the application under test.

In Selenium 3, we may face few issues while capturing Screenshots. To overcome we use aShot utility. Click on below links to see posts related to the normal way of capturing a screenshot and capturing a screenshot using aShot utility.

Capture screenshot using Selenium WebDriver

Full Page Screenshot using aShot utility

Failed Test Cases Screenshot

  1. How to mouse hover on a web element using WebDriver?

By using Actions class

WebElement ele = driver.findElement(By.xpath("xpath")); //Create object 'action' of an Actions class Actions action = new Actions(driver); //Mouseover on an element action.moveToElement(ele).perform();

1

2

3

4

5

WebElement ele = driver.findElement(By.xpath("xpath"));

//Create object 'action' of an Actions class

Actions action = new Actions(driver);

//Mouseover on an element

action.moveToElement(ele).perform();

 

  1. How can we handle web based pop-up?

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

 

  1. How can we handle windows based pop up?

Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT, Robot class etc.

  1. How to handle hidden elements in Selenium WebDriver?

It is one of the most important selenium interview questions.

We can handle hidden elements by using javaScript executor

(JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");

1 (JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");
  1. How can you find Broken Links in a page using Selenium WebDriver?

 

  1. How to find more than one web element in the list?

// To store the list List <WebElement> eleList = driver.findElements(By.xpath("xpath")); // To fetch the size of the list int listSize = eleList.size(); //for loop for (int i=0; i<listSize; i++) {     // Clicking on each link     links.get(i).click();     // Navigating back to the previous page that stores the links     driver.navigate().back(); }

1

2

3

4

5

6

7

8

9

10

11

12

// To store the list

List <WebElement> eleList = driver.findElements(By.xpath("xpath"));

// To fetch the size of the list

int listSize = eleList.size();

//for loop

for (int i=0; i<listSize; i++)

{

// Clicking on each link

links.get(i).click();

// Navigating back to the previous page that stores the links

driver.navigate().back();

}

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

By using JavascriptExecutor

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

1

2

3

4

5

// To initialize the JS object.

JavascriptExecutor JS = (JavascriptExecutor) webdriver;

// To get the site title.

String title = (String)JS.executeScript("return document.title");

System.out.println("Title of the webpage : " + title);

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

In general, we click on an element using click() method in Selenium.

For example:

driver.findElement(By.id("Id Value")).click();

1 driver.findElement(By.id("Id Value")).click();

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor;

1 import org.openqa.selenium.JavascriptExecutor;

Syntax:

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

1

2

JavascriptExecutor js = (JavascriptExecutor) driver;  

js.executeScript(Script,Arguments);

Script – The JavaScript to execute

Arguments – The arguments to the script(Optional). May be empty.

Returns – One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

  1. To type Text in Selenium WebDriver without using sendKeys() method
  2. To click a Button in Selenium WebDriver using JavaScript
  3. To handle Checkbox
  4. To generate Alert Pop window in selenium
  5. To refresh browser window using Javascript
  6. To get innertext of the entire webpage in Selenium
  7. To get the Title of our webpage
  8. To get the domain
  9. To get the URL of a webpage
  10. To perform Scroll on an application using  Selenium
  11. To click on a SubMenu which is only visible on mouse hover on Menu
  12. To navigate to different page using Javascript
  13. How do you read test data from excels?

Test data can efficiently be read from excel using JXL or POI API. POI API has many advantages than JXL.

Click here to see a practical example of using Apache POI.

  1. Is it possible to automate the captcha using Selenium?

No, It’s not possible to automate captcha and bar code reader.

  1. How to handle Ajax calls in Selenium WebDriver?

Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.

AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just because the actual page is not going to refresh.

When you click on a submit button, the required information may appear on the web page without refreshing the browser. Sometimes it may load in a second and sometimes it may take longer. We have no control over loading time. The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)

Some of the methods which are available are as follows:

  1. titleIs() – The expected condition waits for a page with a specific title.

wait.until(ExpectedConditions.titleIs(“Deal of the Day”));

1 wait.until(ExpectedConditions.titleIs(“Deal of the Day”));
  1. elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));

1 wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
  1. alertIsPresent() – The expected condition waits for an alert box to appear.

wait.until(ExpectedConditions.alertIsPresent()) !=null);

1 wait.until(ExpectedConditions.alertIsPresent()) !=null);
  1. textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.

wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));

1 wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));
  1. List some scenarios which we cannot automate using Selenium WebDriver?
  2. Bitmap comparison is not possible using Selenium WebDriver
  3. Automating Captcha is not possible using Selenium WebDriver
  4. We can not read bar code using Selenium WebDriver
  5. What is Object Repository in Selenium WebDriver?

Object Repository is used to store element locator values in a centralized location instead of hard coding them within the scripts. We do create a property file (.properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.

  1. How you build Object Repository in your project?

In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by default in an Object Repository. QTP uses this Object Repository to play back the scripts. Coming to Selenium, there is no default Object Repository concept. It doesn’t mean that there is no Object Repository in Selenium. Even though there is no default one still we could create our own. In Selenium, we call objects as locators (such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS). Object repository is a collection of objects. One of the ways to create Object Repository is to place all the locators in a separate file (i.e., properties file). But the best way is to use Page Object Model. In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular page of a web application are stored in a class.

  1. What is Page Object Model in Selenium?

Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication. Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid framework etc.  A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.

  1. What is Page Factory?

We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.

  1. What is the difference between Page Object Model (POM) and Page Factory?

Page Object is a class that represents a web page and hold the functionality and members.

Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.

  1. What are the advantages of Page Object Model Framework?

Code reusability – We could achieve code reusability by writing the code once and use it in different tests.

Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.

Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.

Readability – Improves readability due to clean separation between test code and page specific code

  1. How can you use the Recovery Scenario in Selenium WebDriver?

By using “Try Catch Block” within Selenium WebDriver Java tests.

try { driver.get("www.SoftwareTestingMaterial.com"); }catch(Exception e){ System.out.println(e.getMessage()); }

1

2

3

4

5

try {

    driver.get("www.SoftwareTestingMaterial.com");

}catch(Exception e){

    System.out.println(e.getMessage());

}

  1. How to Upload a file in Selenium WebDriver?

There are two cases which are majorly used to upload a file in Selenium WebDriver such as using SendKeys Method and using AutoIT Script.

Practical Example.

  1. How to Download a file in Selenium WebDriver?

By using AutoIT script, we could download a file in Selenium WebDriver.

Practical Example

  1. How to run Selenium WebDriver Test from the command line?

Run Java Program using Command Prompt

Run TestNG using Command Prompt

  1. How to switch between frames in Selenium?

By using the following code, we could switch between frames.

driver.switchTo().frame();

1 driver.switchTo().frame();
  1. How to connect a Database in selenium?

As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.

We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).

Practical Example

  1. How To Resize Browser Window Using Selenium WebDriver?

To resize the browser window to particular dimensions, we use ‘Dimension’ class to resize the browser window.

Practical Example

  1. How To Scroll Web Page Down Or UP Using Selenium WebDriver?

JavaScript scrollBy() method scrolls the document by the specified number of pixels.

Practical Example

  1. How To Perform Right Click Action (Context Click) In Selenium WebDriver?

We use Actions class in Selenium WebDriver to do Right-Click (Context Click) action.

Practical Example

  1. How To Perform Double Click Action In Selenium WebDriver?

We use Actions class to do Double click action in selenium.

Practical Example

  1. How To Perform Drag And Drop Action in Selenium WebDriver?

In some applications, we may face a situation to automate drag and drop an item from one location to another location. We could not achieve these using basic elements. Selenium has provided an “Actions” class to handle this kind of scenarios. We overcome this kind of scenarios such as drag and drop using Actions Class.

To achieve this, we use Actions class in Selenium WebDriver.

Practical Example

  1. How To Highlight Element Using Selenium WebDriver?

By using JavascriptExecutor interface, we could highlight the specified element

Practical Example

  1. Have you used any cross browser testing tool to run selenium scripts on cloud?

I have used BrowserStack to run selenium tests on multiple browsers & Multiple operating systems in parallel. Earlier we have made a video on how to use BrowserStack to run selenium scripts on the cloud. Find the link in the description below.

  1. What is desired capabilities?

In Selenium we use desired capabilities to handle SSL certificates in chrome browser

We need to create an instance of DesiredCapabilities

DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();

1 DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();
  1. What is Continuous Integration?

Continuous Integration is abbreviated as CI. Continuous Integration is a development practice which aims to make sure the correctness of a software. After each commit, a suite of tests run automatically and test the software to ensure whether the software is running without any breaks. If any test fails, we will get immediate feedback say “build is broken”.

In simple words, continuous integration is a process of verifying the correctness of a software.

Some of the continuous integration tools are Jenkins, TeamCity, Bamboo, Travis, Circle Ci, Bitbucket.

We can schedule the test suite execution using these CI Tools.

  1. How to achieve Database testing in Selenium?

As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.

Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the Database.  If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve our task. To achieve the Database connection and work on it, we need to use JDBC API Driver.

The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation script. JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming Language and the database.

Using JDBC Driver we could do the following

  1. Establish a Database connection
  2. Send SQL Queries to the Database

iii. Process the results

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

driver.Manage().Cookies.DeleteAllCookies();

1 driver.Manage().Cookies.DeleteAllCookies();

TestNG – Interview Questions:

Here we have dealt with some important TestNG interview questions. If you want to learn more interview questions related to TestNG then here you go. We have a special post on TestNG Interview Questions. Also, you could find TestNG Complete Tutorial here

  1. What is TestNG?

TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration testing.

  1. What are the annotations available in TestNG?

@BeforeTest

@AfterTest

@BeforeClass

@AfterClass

@BeforeMethod

@AfterMethod

@BeforeSuite

@AfterSuite

@BeforeGroups

@AfterGroups

@Test

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

TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception.

Some of the common assertions supported by TestNG are

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

 

  1. How to create and run TestNG.xml?

In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.

 

  1. How to set test case priority in TestNG?

We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical order.

package TestNG; import org.testng.annotations.*; public class PriorityTestCase{     @Test(priority=0)     public void testCase1() {         system.out.println("Test Case 1");     }     @Test(priority=1)     public void testCase2() {             system.out.println("Test Case 2");     } }

1

2

3

4

5

6

7

8

9

10

11

12

package TestNG;

import org.testng.annotations.*;

public class PriorityTestCase{

@Test(priority=0)

public void testCase1() {  

system.out.println("Test Case 1");

}

@Test(priority=1)

public void testCase2() {

system.out.println("Test Case 2");

}

}

Output:

Test Case 1 Test Case 2

1

2

Test Case 1

Test Case 2

  1. What is Parameterized testing in TestNG?

Parameterized tests allow developers to run the same test over and over again using different values.

There are two ways to set these parameters:

  • with testng.xml - Practical Example
  • with Data Providers  – Practical Example
  1. How to run a group of test cases using TestNG?

TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.  This gives you maximum flexibility in how you partition your tests and doesn’t require you to recompile anything if you want to run two different sets of tests back to back.

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

@Test (groups = { "smokeTest", "functionalTest" }) public void loginTest(){ System.out.println("Logged in successfully"); }

1

2

3

4

@Test (groups = { "smokeTest", "functionalTest" })

public void loginTest(){

System.out.println("Logged in successfully");

}

View Complete Post

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

Ans. TestNG listeners are used to configure reports and logging. One of the most widely used listeners in TestNG is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We should implement this interface creating a listener class of our own. Next, we should add the listeners annotation (@Listeners) in the Class which was created.

  1. How can we create a data-driven framework using TestNG?

By using @DataProvider annotation,  we can create a Data Driven Testing Framework.

@DataProvider(name="getData")     public Object[][] getData(){         //Object [][] data = new Object [rowCount][colCount];         Object [][] data = new Object [2][2];                 data [0][0] = "FirstUid";         data [0][1] = "FirstPWD";                 data[1][0] = "SecondUid";         data[1][1] = "SecondPWD";                 return data;             }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@DataProvider(name="getData")

public Object[][] getData(){

//Object [][] data = new Object [rowCount][colCount];

Object [][] data = new Object [2][2];

data [0][0] = "FirstUid";

data [0][1] = "FirstPWD";

data[1][0] = "SecondUid";

data[1][1] = "SecondPWD";

return data;

}

Practical Example

  1. Where you have applied OOPS in Automation Framework?

Check this link

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

In Chrome, we can use ChromeOptions as shown below.

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

1

2

3

ChromeOptions options = new ChromeOptions();

options.addArguments("disable-infobars");

WebDriver player = new ChromeDriver(options);

 

 

 


Top 100 SeLENIUM Testing Interview Q & A  

1) What is Selenium and what is composed of?

Selenium is a suite of tools for automated web testing.  It is composed of

  • Selenium IDE (Integrated Development Environment) :  It is a tool for recording and playing back.  It is a firefox plugin
  • WebDriver and RC:  It provide the APIs for a variety of languages like Java, .NET, PHP, etc. With most of the browsers Webdriver and RC works.
  • Grid: With the help of Grid you can distribute tests on multiple machines so that test can be run parallel which helps in cutting down the time required for running in browser test suites

 

2) What is Selenium 2.0 ?

Web Testing tools Selenium RC and WebDriver are consolidated in single tool in Selenium 2.0

3) Mention what is Selenium 3.0?

Selenium 3.0 is the latest version of Selenium. It has released 2 beta versions of selenium 3.0 with few of the below changes:

Here are few new features added to Selenium 3.0

Beta 1 updates Beta 2 updates (Only for Java)
  • Minimum Java version is now 8+
  • System property webdriver.firefox.marionette now forces the server in marionette or legacy firefox driver mode, ignoring any related Desired Capability
  • It will support for Firefox Via Mozilla’s geckodriver
  • Grid fixes NPE’s on registration when -browser not specified
  • Support for Edge is provided by MS
  • It now supports Safari on MacOS via Apple’s own Safari driver
  • Update GeckoDriver –port argument in all bindings

4) How will you find an element using Selenium?

In Selenium every object or control in a web page is referred as an elements, there are different ways to find an element in a web page they are

  • ID
  • Name
  • Tag
  • Attribute
  • CSS
  • Linktext
  • PartialLink Text
  • Xpath etc

5) List out the test types that are supported by Selenium?

For web based application testing selenium can be used

The test types can be supported are

  1. a) Functional, Learn More about Functional Testing.
  2. b) Regression

For post release validation with continuous integration automation tool could be used

  1. a) Jenkins
  2. b) Hudson
  3. c) Quick Build
  4. d) CruiseCont

6) Explain what is assertion in Selenium and what are the types of assertion?

Assertion is used as a  verification point. It verifies that the state of the application conforms to what is expected.  The types of assertion are “assert” , “verify” and “waifFor”.

7) Mention what is the use of X-path?

X-Path is used to find the WebElement in web pages. It is also useful in identifying the dynamic elements.

Refer Complete Guide on XPath

8) Explain the difference between single and double slash in X-path? Single slash ‘/ ’

  • Single slash ( / ) start selection from the document node
  • It allows you to create ‘absolute’ path expressions

Double Slash ‘// ’

  • Double slash ( // ) start selection matching anywhere in the document
  • It enables to create ‘relative’ path expressions

9) List out the technical challenges with Selenium? Technical challenges with Selenium are

  • Selenium supports only web based applications
  • It does not support the Bitmap comparison
  • For any reporting related capabilities have to depend on third party tools
  • No vendor support for tool compared to commercial tools like HP UFT
  • As there is no object repository concept in Selenium, maintainability of objects becomes difficult

10) What is the difference between type keys and type commands ?

TypeKeys() will trigger JavaScript event in most of the cases whereas .type() won’t. Type key populates the value attribute using JavaScript whereas .typekeys() emulates like actual user typing

11) What is the difference between verify and assert commands?

Assert:  Assert allows to check whether an element is on the page or not. The test will stop on the step failed, if the asserted element is not available. In other words, the test will terminated at the point where check fails.

Verify: Verify command will check whether the element is on the page, if it is not then the test will carry on executing.  In verification, all the commands are going to run guaranteed even if any of test fails.

12) What is JUnit Annotations and what are different types of annotations which are useful ?

In JAVA a special form of syntactic meta-data can be added to Java source code, this is know as Annotations.  Variables, parameters, packages, methods and classes are annotated some of the Junit annotations which can be useful are

  • Test
  • Before
  • After
  • Ignore
  • BeforeClass
  • AfterClass
  • RunWith

13) While using click command can you use screen coordinate? 

To click on specific part of element, you would need to use clickAT command.  ClickAt command accepts element locator and x, y co-ordinates as arguments- clickAt (locator, cordString)

14)  What are the advantages of Selenium?

  • It supports C#, PHP, Java, Perl, Phython
  • It supports different OS like Windows, Linux and Mac OS
  • It has got powerful methods to locate elements (Xpath, DOM , CSS)
  • It has highly developer community supported by Google

15) Why testers should opt for Selenium and not QTP? Selenium is more popular than QTP as

  • Selenium is an open source whereas QTP is a commercial tool
  • Selenium is used specially for testing web based applications while QTP can be used for testing client server application also
  • Selenium supports Firefox, IE, Opera, Safari  on operating systems like Windows, Mac, Linux etc. however QTP is limited to Internet Explorer on Windows.
  • Selenium supports many programming languages like Ruby, Perl, Python whereas QTP supports only VB script

16) What are the four parameter you have to pass in Selenium? Four parameters that you have to pass in Selenium are

  • Host
  • Port Number
  • Browser
  • URL

17) What is the difference between setSpeed() and sleep() methods?

Both will delay the speed of execution.

Thread.sleep () :  It will stop the current (java) thread for the specified period of time.  Its done only once

  • It takes a single argument in integer format

Ex: thread.sleep(2000)- It will wait for 2 seconds

  • It waits only once at the command given at sleep

SetSpeed () :  For specific amount of time it will stop the execution for every selenium command.

  • It takes a single argument in integer format

Ex: selenium.setSpeed(“2000”)- It will wait for 2 seconds

  • Runs each command  after setSpeed delay by the number of milliseconds mentioned in set Speed

This command is useful for demonstration purpose or if you are using a slow web application

18) What is same origin policy? How you can avoid same origin policy?

The “Same Origin Policy” is introduced for security reason, and it ensures that content of your site will never be accessible by a script from another site.  As per the policy, any code loaded within the browser can only operate within that website’s domain.

To avoid “Same Origin Policy” proxy injection method is used, in proxy injection mode the Selenium Server acts as a client configured HTTP proxy , which sits between the browser and application under test and then masks the AUT under a fictional URL

19) What is heightened privileges browsers?

The purpose of heightened privileges is similar to Proxy Injection, allows websites to do something that are not commonly permitted.  The key difference is that the browsers are launched in a special mode called heightened privileges.  By using these browser mode, Selenium core can open the AUT directly and also read/write its content without passing the whole AUT through the Selenium RC server.

20) How you can use “submit” a form using Selenium?

You can use “submit” method on element to submit form-

element.submit () ;

Alternatively, you can use click method on the element which does form submission

21) What are the features of TestNG and list some of the functionality in TestNG which makes it more effective?

TestNG is a testing framework based on JUnit and NUnit to simplify a broad range of testing needs, from Unit Testing to Integration Testing. And the functionality which makes it efficient testing framework are

  • Support for annotations
  • Support for data-driven testing
  • Flexible test configuration
  • Ability to re-execute failed test cases

22) Mention what is the difference between Implicit wait and Explicit wait?

Implicit Wait: Sets a timeout for all successive Web Element searches. For the specified amount of time it will try looking for element again and again before throwing a NoSuchElementException.  It waits for elements to show up.

Explicit Wait :  It is a one-timer, used for a particular search.

23) Which attribute you should consider throughout the script in frame for “if no frame Id as well as no frame name”?

You can use…..driver.findElements(By.xpath(“//iframe”))….

This will return list of frames.

You will ned to  switch to each and every frame and search for locator which we want.

Then break the loop

24) Explain what is the difference between find elements () and find element () ?

find element ():

It finds the first element within the current page using the given “locating mechanism”.  It returns a single WebElement

findElements () : Using the given “locating mechanism” find all the elements within the current page.  It returns a list of web elements.

25) Explain what are the JUnits annotation linked with Selenium?

The JUnits annotation linked with Selenium are

  • @Before public void method() – It will perform the method () before each test, this method can prepare the test
  • @Test public void method() – Annotations @Test identifies that this method is a test method environment
  • @After public void method()- To execute a method before this annotation is used, test method must start with test@Before

26) Explain what is Datadriven framework and Keyword driven?

Datadriven framework:  In this framework, the test data is separated and kept outside the Test Scripts, while Test Case logic resides in Test Scripts.  Test data is read from the external files ( Excel Files) and are loaded into the variables inside the Test Script.  Variables are used for both for input values and for verification values.

Keyworddriven framework: The keyword driven frameworks requires the development of data tables and keywords, independent of the test automation.  In a keyword driven test, the functionality of the application under test is documented in a table as well as step by step instructions for each test.

27) Explain how you can login into any site if it’s showing any authentication popup for password and username?

Pass the username and password with url

28) Explain how to assert text of webpage using selenium 2.0 ?

WebElement el = driver.findElement(By.id(“ElementID”))

//get test from element and stored in text variable

String text = el.getText();

//assert text from expected

Assert.assertEquals(“Element Text”, text);

29) Explain what is the difference between Borland Silk and Selenium?

                          Silk Test Tool                         Selenium Test Tool
  • Borland Silk test is not a free testing tool
  • Selenium is completely free test automation tool
  • Silk test supports only Internet Explorer and Firefox
  • Selenium supports many browsers like Internet Explorer, Firefox, Safari, Opera and so on
  • Silk test uses test scripting language
  • Selenium suite has the flexibility to use many languages like Java, Ruby,Perl and so on
  • Silk test can be used for client server applications
  • Selenium can be used for only web application

30) What is Object Repository ?

An object repository is an essential entity in any UI automations which allows a tester to store all object that will be used in the scripts in one or more centralized locations rather than scattered all over the test scripts.

31) Explain how Selenium Grid works?

Selenium Grid sent the tests to the hub. These tests are redirected to Selenium Webdriver, which launch the browser and run the test.  With entire test suite, it allows for running tests in parallel.

32) Can we use Selenium grid for performance testing?

Yes. But not as effectively as a dedicated Performance Testing tool like Loadrunner.

33)  List the advantages of Webdriver over Selenium Server?

  • If you are using Selenium-WebDriver, you don’t need the Selenium Server as it is using totally different technology
  • Selenium Server provides Selenium RC functionality which is used for Selenium 1.0 backwards compatibility
  • Selenium Web driver makes direct calls to browser using each browsers native support for automation, while Selenium RC requires selenium server to inject Javascript into the browser

34)  Mention what are the capabilities of Selenium WebDriver or Selenium 2.0 ?

WebDriver should be used when requiring improvement support for

  • Handling multiple frames, pop ups , multiple browser windows and alerts
  • Page navigation and drag & drop
  • Ajax based UI elements
  • Multi browser testing including improved functionality for browser not well supported by Selenium 1.0

35)  While injecting capabilities in webdriver to perform tests on a browser which is not supported by a webdriver what is the limitation that one can come across?

Major limitation of injecting capabilities is that “findElement” command may not work as expected.

36)  Explain how you can find broken images in a page using Selenium Web driver ?

To find the broken images in a page using Selenium web driver is

  • Get XPath and get all the links in the page using tag name
  • In the page click on each and every link
  • Look for 404/500 in the target page title

37)  Explain how you can handle colors in web driver?

To handle colors in web driver you can use

Use getCssValue(arg0) function to get the colors by sending ‘color’ string as an argument

38)  Using web driver how you can store a value which is text box?

You can use following command to store a value which is text box using web driver

driver.findElement(By.id(“your Textbox”)).sendKeys(“your keyword”);

39)  Explain how you can switch between frames?

To switch between frames webdrivers [ driver.switchTo().frame() ] method takes one of the three possible arguments

  • A number:  It selects the number by its (zero-based) index
  • A number or ID: Select a frame by its name or ID
  • Previously found WebElement: Using its previously located WebElement select a frame

40)  Mention 5 different exceptions you had in Selenium web driver?

The 5 different exceptions you had in Selenium web drivers are

  • WebDriverException
  • NoAlertPresentException
  • NoSuchWindowException
  • NoSuchElementException
  • TimeoutException

41)  Explain using Webdriver how you can perform double click ?

You can perform double click by using

  • Syntax- Actions act = new Actions (driver);
  • act.doubleClick(webelement);

42) How will you use  Selenium to upload a file ?

You can use “type”command to type in a file input box of upload file. Then, you have to use “Robot” class in JAVA to make file upload work.

43) Which web driver implementation is fastest?

HTMLUnit Driver implementation is fastest, HTMLUnitDriver does not execute tests on browser but plain http request, which is far quick than launching a browser and executing tests

44) Explain how you can handle frames using Selenium 2.0 ?

To bring control on HTML frame you can use “SwitchTo” frame method-

driver.switchTo().frame(“frameName”);

To specify a frame you can use index number

driver.switchTo().frame(“parentFrame.4.frameName”);

This would bring control on frame named- “frameName” of the 4th sub frame names “parentFrame”

45) What is the difference between getWindowhandles() and getwindowhandle() ?

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

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

46) Explain how you can switch back from a frame?

To switch back from a frame use method defaultContent()

Syntax-driver.switchTo().defaultContent();

47) List out different types of locators?

Different types of locators are

  • By.id()
  • By.name()
  • By.tagName()
  • By.className()
  • By.linkText()
  • By.partialLinkText()
  • By.xpath
  • By.cssSelector()

48) What is the command that is used in order to display the values of a variable into the output console or log?

  • In order to display a constant string, command can be used is echo <constant string>
  • If order to display the value of a variable you can use command like echo ${variable name>>

Above is using PHP. If you are using Java, replace echo with System.out.println

49)   Explain how you can use recovery scenario with Selenium?

Recovery scenarios depends upon the programming language you use.  If you are using Java then you can use exception handling to overcome same.  By using “Try Catch Block” within your Selenium WebDriver Java tests

50) Explain how to iterate through options in test script?

To iterate through options in test script you can loop features of the programming language, for example to type different test data in a text box you can use “for” loop in Java

// test data collection in an array

String[ ] testData = { “test1” , “test2” , “test3” } ;

// iterate through each test data

For  (string s: test data) { selenium.type ( “elementLocator”, testData) ; }

51) How can you prepare customized html report using TestNG in hybrid framework ?

There are three ways

  • Junit: With the help of ANT
  • TestNG: Using inbuilt default.html to get the HTML report. Also XST reports from ANT, Selenium, Testng combinations
  • Using our own customized reports using XSL jar for converting XML content to HTML

52) From your test script how you can create html test report?

To create html test report there are three ways

  • TestNG:  Using inbuilt default.html to get the HTML report. Also XLST reports from ANT, Selenium, TestNG combination
  • JUnit: With the help of ANT
  • Using our own customized reports using XSL jar for converting XML content to HTML

53)  Explain how you can insert a break point in Selenium IDE ?

In Selenium IDE to insert a break point

  • Select “Toggle break point” by right click on the command in Selenium IDE
  • Press “B” on the keyboard and select the command in Selenium IDE
  • Multiple break points can be set in Selenium IDE

54)  Explain in Selenium IDE how can you debug the tests?

  • Insert a break point from the location from where you want to execute test step by step
  • Run the test case
  • At the given break point execution will be paused
  • To continue with the next statement click on the blue button
  • Click on the “Run” button to continue executing all the commands at a time

55)  What is Selenese and what are the types of Selenese ?

Selenese is a selenium set of command which are used for running the test

There are three types of Selenese

  • Actions: It is used for performing the operations and interactions with the target elements
  • Assertions: It is used as a check points
  • Accessors: It is used for storing the values in a variable

56)  Explain what are the limitations of Selenium IDE?

The limitations of Selenium IDE

  • Exceptional handling is not present
  • Selenium IDE uses only HTML languages
  • External databases reading is not possible with IDE
  • Reading from the external files like .txt, .xls is not possible
  • Conditional or branching statements execution like if,else,  select statements is not possible

57)  What are the two modes of views in Selenium IDE ?

Either Selenium IDE can be opened as a pop up window or in side bar

58)  In selenium IDE what are the element locators that can be used to locate elements on web page?

In selenium there are mainly 4 locators that are used

  • X-path locators
  • Css locators
  • Html id
  • Html name

59)  In Selenium IDE how you can generate random numbers and dates for test data ?

In Selenium IDE you can generate random numbers by using Java Script

type

css=input#s

javascript{Math.random()}

And for

type

css=input#s

javascript{new Date()}

60)  How you can convert any Selenium IDE tests from Selenese to another language?

You can use the format option of Selenium IDE to convert tests into another programming language

61)  Using Selenium IDE is it possible to get data from a particular html table cell ?

You can use the “storeTable” command

Example store text from cell 0,2 from an html table

storeTable

Css=#table 0.2

textFromCell

62)  Explain what can cause a Selenium IDE test to fail?

  • When a locator has changed and Selenium IDE cannot locate the element
  • When element Selenium IDE waiting to access did not appear on the web page and the operation timed out
  • When element Selenium IDE was trying to access was not created

63)  Explain how you can debug the tests in Selenium IDE ?

  • Insert a break point from the location where you want to execute step by step
  • Run the test case
  • At the given break point execution will be paused
  • To continues with the next step click on the Blue button
  • To run commands at a time click on run button

64)  From Selenium IDE how you can execute a single line?

From Selenium IDE single line command can be executed in two ways

  • Select “Execute this command” by right clicking on the command in Selenium IDE
  • Press “X” key on the keyboard after selecting the command in Selenium IDE

65)  In which format does source view shows your script in Selenium IDE ?

In Selenium IDE source view shows your script in XML format

66)  Explain how you can insert a start point in Selenium IDE?

In two ways selenium IDE can be set

  • Press “S” key on the keyboard and select the command in Selenium IDE
  • In Seleniun IDE right click on the command and the select  “Set / Clear Start Point”

67)  What if you have written your own element locator and how would you test it?

To test the locator one can use “Find Button” of Selenium IDE, as you click on it, you would see on screen an element being highlighted provided your element locator is right or or else an error message will be displayed

68)  What is regular expressions? How you can use regular expressions in Selenium ?

A regular expression is a special text string used for describing a search pattern. In Selenium IDE regular expression can be used with the keyword- regexp: as a prefix to the value and patterns needs to be included for the expected values.

69)  What are core extension ?

If you want to “extend” the defualt functionality provided by Selenium Function Library , you can create a Core Extension. They are also called “User Extension”. You can even download ready-made Core Extension created by other Selenium enthusiats.

70)  How will you handle working with multiple windows in Selenium ?

We can use the command selectWindow to switch between windows. This command uses the title of Windows to identify which window to switch to.

71)  How will you verify the specific position of an web element

You can use verifyElementPositionLeft & verifyElementPositionTop. It does a pixel comparison of the position of the element from the Left and Top of page respectively

72)  How can you retrive the message in an alert box ?

You can use the storeAlert command which will fetch the message of the alert pop up and store it in a variable.

73) What is selenium RC (Remote Control)?

Selenium IDE have limitations in terms of browser support and language support. By using Selenium RC limitation can be diminished.

  • On different platforms and  different web browser for automating web application  selenium RC is used with languages like Java, C#, Perl, Python
  • Selenium RC is a java based and using any language it can interact with the web application
  • Using server you can bypass the restriction and run your automation script running against any web application

74) Why Selenium RC is used?

Selenium IDE does not directly support many functions like condition statements, Iteration, logging and reporting of test results, unexpected error handling and so on as IDE supports only HTML language.  To handle such issues Selenium RC is used  it supports the language like Perl, Ruby, Python, PHP using these languages we can write the program to achieve the IDE issues.

75) Explain what is the main difference between web-driver and RC ?

The main difference between Selenium RC and Webdriver is that, selenium RC injects javascript function into browsers when the page is loaded. On the other hand, Selenium Webdriver drives the browser using browsers built in support

76) What are the advantages of RC?

Advantages of RC are

  • Can read or write data from/ to .xls, .txt, etc
  • It can handle dynamic objects and Ajax based UI elements
  • Loops and conditions can be used for better performance and flexibility
  • Support many Programming languages and Operating Systems
  • For any JAVA script enabled browser Selenium RC can be used

77) Explain what is framework and what are the frameworks available in RC?

A collection of libraries and classes is known as Framework and they are helpful when testers has to automate test cases. NUnit, JUnit, TestNG, Bromine, RSpec, unittest are some of the frameworks available in RC .

78) How can we handle pop-ups in RC ?

To handle pop-ups in RC , using selectWindow method, pop-up window will be selected and windowFocus method will let the control from current window to pop-up windows and perform actions according to script

79) What are the technical limitations while using Selenium RC?

Apart from “same origin policy” restriction from js, Selenium is also restricted from exercising anything that is outside browser.

80) Can we use Selenium RC to drive tests on two different browsers on one operating system without Selenium Grid?

Yes, it is possible when you are not using JAVA testing framework.  Instead of using Java testing framework if you are using java client driver of selenium then TestNG allows you to do this.  By using “parallel=test” attribute you can set tests to be executed in parallel and can define two different tests, each using different browser.

81) Why to use TestNG with Selenium RC ?

If you want full automation against different server and client platforms, You need a way to invoke the tests from a command line process, reports that tells you what happened and flexibility in how you create your test suites. TestNG gives that flexibility.

82) Explain how you can capture server side log Selenium Server?

To capture server side log in Selenium Server, you can use command

  • java –jar .jar –log selenium.log

83) Other than the default port 4444 how you can run Selenium Server?

You can run Selenium server on java-jar selenium-server.jar-port other than its default port

84) How Selenium grid hub keeps in touch with RC slave machine?

At predefined time selenium grid hub keeps polling all RC slaves to make sure it is available for testing.  The deciding parameter is called “remoteControlPollingIntervalSeconds” and is defined in “grid_configuration.yml”file

85) Using Selenium how can you handle network latency?

To handle network latency you can use driver.manage.pageloadingtime for network latency

86) To enter values onto text boxes what is the command that can be used?

To enter values onto text boxes we can use command sendkeys()

87) How do you identify an object using selenium?

To identify an object using Selenium you can use

isElementPresent(String locator)

isElementPresent takes a locator as the argument and if found returns a Boolean

88) In Selenium what are Breakpoints and Startpoints?

  • Breakpoints: When you implement a breakpoint in your code, the execution will stop right there. This helps you to verify that your code is working as expected.
  • StartpointsStartpoint indicates the point from where the execution should begin. Startpoint can be used when you want to run the testscript from the middle of the code or a breakpoint.

89) Mention why to choose Python over Java in Selenium?

Few points that favor Python over Java to use with Selenium is,

  • Java programs tend to run slower compared to Python programs.
  • Java uses traditional braces to start and ends blocks, while Python uses indentation.
  • Java employs static typing, while Python is dynamically typed.
  • Python is simpler and more compact compared to Java.

90) Mention what are the challenges in Handling Ajax Call in Selenium Webdriver?

The challenges faced in Handling Ajax Call in Selenium Webdriver are

  • Using "pause" command for handling Ajax call is not completely reliable. Long pause time makes the test unacceptably slow and increases the testing time. Instead, "waitforcondition" will be more helpful in testing Ajax applications.
  • It is difficult to assess the risk associated with particular Ajax applications
  • Given full freedom to developers to modify Ajax application makes the testing process challenging
  • Creating automated test request may be difficult for testing tools as such AJAX application often use different encoding or serialization technique to submit POST data.

91) Mention what is IntelliJ?

Intellij is an IDE that helps you to write better and faster code for Selenium. Intellij can be used in the option to Java bean and Eclipse.

92) Mention in what ways you can customize TestNG report?

You can customize TestNG report in two ways,

  • Using ITestListener Interface
  • Using IReporter Interface

93) To generate pdf reports mention what Java API is required?

To generate pdf reports, you need Java API IText.

94) Mention what is Listeners in Selenium WebDriver?

In Selenium WebDriver, Listeners "listen" to the event defined in the selenium script and behave accordingly. It allows customizing TestNG reports or logs. There are two main listeners i.e. WebDriver Listeners and TestNG Listeners.

95) Mention what are the types of Listeners in TestNG?

The types of Listeners in TestNG are,

  • IAnnotationTransformer
  • IAnnotationTransformer2
  • IConfigurable
  • IConfigurationListener
  • IExecutionListener
  • IHookable
  • IInvokedMethodListener
  • IInvokedMethodListener2
  • IMethodInterceptor
  • IReporter
  • ISuiteListener
  • ITestListener

96) Mention what is desired capability? How is it useful in terms of Selenium?

The desired capability is a series of key/value pairs that stores the browser properties like browser name, browser version, the path of the browser driver in the system, etc. to determine the behavior of the browser at run time.

For Selenium,

  • It can be used to configure the driver instance of Selenium WebDriver.
  • When you want to run the test cases on a different browser with different operating systems and versions.

97) For Database Testing in Selenium Webdriver what API is required?

For Database Testing in Selenium Webdriver, you need JDBC (Java Database Connectivity) API. It allows you to execute SQL statements.

98) Mention when to use AutoIT?

Selenium is designed to automate web-based applications on different browsers. But to handle window GUI and non-HTML popups in the application you need AutoIT. know more about

99) Mention why do you need Session Handling while working with Selenium?

While working with Selenium, you need Session Handling. This is because, during test execution, the Selenium WebDriver has to interact with the browser all the time to execute given commands. At the time of execution, it is also possible that, before current execution completes, someone else starts execution of another script, in the same machine and in the same type of browser. So to avoid such situation you need Session Handling.

100) Mention what are the advantages of Using Git Hub For Selenium?

The advantages of Using Git Hub for Selenium are

  • Multiple people when they work on the same project they can update project details and inform other team members simultaneously.
  • Jenkins can help you to build the project from the remote repository regularly. This helps you to keep track of failed builds.

Prep Up For your Job Interview!!! Go through Selenium Tutorial to be better prepared.  Test your knowledge with Selenium Quiz

 

Python Interview Q&A

Python Interview Q&A

SET 1 : Python Interview Questions & Answers

1) What is Python? What are the benefits of using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

2) What is PEP 8?

PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

3) What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

4) How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

5) How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

6) What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

7) What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

8) What is the difference between list and tuple?

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

9) How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

10) What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

11) What are the built-in type does python provides?

There are mutable and Immutable types of Pythons built in types Mutable built-in types

  • List
  • Sets
  • Dictionaries

Immutable built-in types

  • Strings
  • Tuples
  • Numbers

12) What is namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

13) What is lambda in Python?

It is a single expression anonymous function often used as inline function.

14) Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

15) What is pass in Python?

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

16) In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like list.

17) What is unittest in Python?

A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.

18) In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

19) What are generators in Python?

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

20) What is docstring in Python?

A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

21) How can you copy an object in Python?

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

22) What is negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

23) How you can convert a number to a string?

In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().

24) What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

25) What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

26) Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

27) How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

28) Explain how can you make a Python Script executable on Unix?

To make a Python Script executable on Unix, you need to do two things,

  • Script file's mode must be executable and
  • the first line must begin with # ( #!/usr/local/bin/python)

29) Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

30) Explain how can you generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating point number in the range [0,1)

31) Explain how can you access a module written in Python from C?

You can access a module written in Python from C by following method,

Module = =PyImport_ImportModule("<modulename>");

32) Mention the use of // operator in Python?

It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

33) Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners
  • Having the built-in data types saves programming time and effort from declaring variables

34) Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

35) Explain what is Flask & its benefits?

Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.

36) Mention what is the difference between Django, Pyramid, and Flask?

Flask is a "microframework" primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.

Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

Like Pyramid, Django can also used for larger applications. It includes an ORM.

37) Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads

38) Explain what is the common way for the Flask script to work?

The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

39) Explain how you can access sessions in Flask?

A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

40) Is Flask an MVC model and if yes give an example showing MVC pattern for your application?

Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example

from flask import Flask

app = Flask(_name_)

@app.route("/")

Def hello():

return "Hello World"

app.run(debug = True)

In this code your,

  • Configuration part will be

from flask import Flask

app = Flask(_name_)

  • View part will be

@app.route("/")

Def hello():

return "Hello World"

  • While you model or main part will be

app.run(debug = True)

41) Explain database connection in Python Flask?

Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

  • before_request() : They are called before a request and pass no arguments
  • after_request() : They are called after a request and pass the response that will be sent to the client
  • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.

42) You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server?

The data in the failed server won't get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.

43) Explain how you can minimize the Memcached server outages in your Python Development?

  • When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
  • Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
  • Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
  • Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached

44) Explain what is Dogpile effect? How can you prevent this effect?

Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value.

45) Explain how Memcached should not be used in your Python project?

  • Memcached common misuse is to use it as a data store, and not as a cache
  • Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
  • Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
  • Memcached does not offer any form of security either in encryption or authentication

SET 2 : Python Interview Questions & Answers

Q1. What is the difference between list and tuples?

LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)

Q2. What are the key features of Python?

  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string" without error
  • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private), the justification for this point is given as “we are all adults here”
  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
  • Python finds use in many spheres – web applications, automation, scientific modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.

Q3. What is the difference between deep and shallow copy?

Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

Q4. How is Multithreading achieved in Python?

Ans:

  1. Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
  2. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  3. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
  4. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

Q5. How can the ternary operators be used in python?

Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

Syntax:

The Ternary operator will be given as:

[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

Python Programming Certification CourseWatch The Course Preview

Q6. How is memory managed in Python?

Ans:

  1. Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
  2. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
  3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.

Q7. Explain Inheritance in Python with an example.

Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  1. Single Inheritance – where a derived class acquires the members of a single super class.
  2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  3. Hierarchical inheritance – from one base class you can inherit any number of child classes
  4. Multiple inheritance – a derived class is inherited from more than one base class.

Q8. Explain what Flask is and its benefits?

Ans: Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

Q9. What is the usage of help() and dir() function in Python?

Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.

  1. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
  2. Dir() function: The dir() function is used to display the defined symbols.

Q10. Whenever Python exits, why isn’t all the memory de-allocated?

Ans:

  1. Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
  2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
  3. On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.

Q11. What is dictionary in Python?

Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

 

1 print dict[Country]

India

1 print dict[Capital]

Delhi

1 print dict[PM]

Modi

Q12. What is monkey patching in Python?

Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

Consider the below example:

1

2

3

4

# m.py

class MyClass:

def f(self):

print "f()"

We can then run the monkey-patch testing like this:

1

2

3

4

5

6

7

import m

def monkey_f(self):

print "monkey_f()"

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

The output will be as below:

monkey_f()

As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.

Q13. What does this mean: *args, **kwargs? And why would we use it?

Ans: We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargsis used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

Q14. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.

Ans:  Let us first write a multiple line solution and then convert it to one liner code.

1

2

3

4

5

6

with open(SOME_LARGE_FILE) as fh:

count = 0

text = fh.read()

for character in text:

   if character.isupper():

count += 1

We will now try to transform this into a single line.

1 count sum(1 for line in fh for character in line if character.isupper())

Q15. What are negative indexes and why are they used?

Ans: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Q16. How can you randomize the items of a list in place in Python?

Ans: Consider the example shown below:

1

2

3

4

from random import shuffle

x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']

shuffle(x)

print(x)

The output of the following code is as below.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

Trending Courses in this category

Python Programming Certification Course

5 (1750)

5k Learners Enrolled Live Class

Best Price 16,015  17,795

Similar CoursesPython Certification Training for Data ScienceData Science Certification Course using RMachine Learning Certification Training using Python

Q17. What is the process of compilation and linking in python?

Ans: The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that is required in this as:

  1. Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
  2. Place this file in the Modules/ directory of the distribution which is getting used.
  3. Add a line in the file Setup.local that is present in the Modules/ directory.
  4. Run the file using spam file.o
  5. After successful run of this rebuild the interpreter by using the make command on the top-level directory.
  6. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

Q18. Write a sorting algorithm for a numerical dataset in Python.

Ans: The following code can be used to sort a list in Python:

1

2

3

4

list = ["1", "4", "0", "6", "9"]

list = [int(i) for i in list]

list.sort()

print (list)

Q19. Looking at the below code, write down the final values of A0, A1, …An.

1

2

3

4

5

6

7

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))

A1 = range(10)A2 = sorted([i for i in A1 if i in A0])

A3 = sorted([A0[s] for s in A0])

A4 = [i for i in A1 if i in A3]

A5 = {i:i*i for i in A1}

A6 = [[i,i*i] for i in A1]

print(A0,A1,A2,A3,A4,A5,A6)

Ans: The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Q20. Explain split(), sub(), subn() methods of “re” module in Python.

Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:

  • split() – uses a regex pattern to “split” a given string into a list.
  • sub() – finds all substrings where the regex pattern matches and then replace them with a different string
  • subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

Q21. How can you generate random numbers in Python?

Ans: Random module is the standard module that is used to generate the random number. The method is defined as:

1

2

import random

random.random

The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates the random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates different instance of individual threads. The other random generators that are used in this are:

  1. randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
  2. uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
  3. normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
  4. The Random class that is used and instantiated creates an independent multiple random number generators.

Q22. What is the difference between range & xrange?

Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

Python Programming Certification CourseWatch The Course Preview

Q23. What is pickling and unpickling?

Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

Django – Python Interview Questions

Q24. Mention the differences between Django, Pyramid and Flask.

Ans:

  • Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
  • Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
  • Django can also used for larger applications just like Pyramid. It includes an ORM.

Q25. Discuss the Django architecture.

Ans: Django MVT Pattern:

Figure:  Python Interview Questions – Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

Q26. Explain how you can set up the Database in Django.

Ans: You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.

  • Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
  • Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.
  • If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.

Django uses SQLite as default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.

We will add the following lines of code to the setting.py file:

1

2

3

4

5

6

DATABASES = {

    'default': {

         'ENGINE' : 'django.db.backends.sqlite3',

         'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),

    }

}

Q27. Give an example how you can write a VIEW in Django?

Ans: This is how we can use write a view in Django:

1

2

3

4

5

6

7

from django.http import HttpResponse

import datetime

def Current_datetime(request):

    now = datetime.datetime.now()

    html = "<html><body>It is now %s</body></html>" % now

    return HttpResponse(html)

Returns the current date and time, as an HTML document

Q28. Mention what the Django templates consists of.

Ans: The template is a simple text file.  It can create any text-based format like XML, CSV, HTML, etc.  A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

Figure: Python Interview Questions – Django Template

Q29. Explain the use of session in Django framework?

Ans: Django provides session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.

Figure: Python Interview Questions – Django Framework

So the data itself is not stored client side. This is nice from a security perspective.

Q30. List out the inheritance styles in Django.

Ans: In Django, there is three possible inheritance styles:

  1. Abstract Base Classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model.
  2. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
  3. Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.

Trending Courses in this category

Python Programming Certification Course

5 (1750)

5k Learners Enrolled Live Class

Best Price 16,015  17,795

Similar CoursesPython Certification Training for Data ScienceData Science Certification Course using RMachine Learning Certification Training using Python

Web Scraping – Python Interview Questions

Q31. How To Save An Image Locally Using Python Whose URL Address I Already Know?

Ans: We will use the following code to save an image locally from an URL address

1

2

import urllib.request

urllib.request.urlretrieve("URL", "local-filename.jpg")

Q32. How can you Get the Google cache age of any URL or web page?

Ans: Use the following URL format:

http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE

Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for. For example, to check the Google Webcache age of edureka.co you’d use the following URL:

http://webcache.googleusercontent.com/search?q=cache:edureka.co

Q33. You are required to scrap data from IMDb top 250 movies page. It should only have fields movie name, year, and rating.

Ans: We will use the following lines of code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from bs4 import BeautifulSoup

import requests

import sys

url = 'http://www.imdb.com/chart/top'

response = requests.get(url)

soup = BeautifulSoup(response.text)

tr = soup.findChildren("tr")

tr = iter(tr)

next(tr)

for movie in tr:

title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]

year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]

rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]

row = title + ' - ' + year + ' ' + ' ' + rating

print(row)

The above code will help scrap data from IMDb’s top 250 list

Data Analysis – Python Interview Questions

Q34. What is map function in Python?

Ans: map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

Q35. How to get indices of N maximum values in a NumPy array?

Ans: We can get the indices of N maximum values in a NumPy array using the below code:

1

2

3

import numpy as np

arr = np.array([1, 3, 2, 4, 5])

print(arr.argsort()[-3:][::-1])

Output

[ 4 3 1 ]

Q36. How do you calculate percentiles with Python/ NumPy?

Ans: We can calculate percentiles with the following code

1

2

3

4

import numpy as np

a = np.array([1,2,3,4,5])

p = np.percentile(a, 50)  #Returns 50th percentile, e.g. median

print(p)

Output

3

Q37. What advantages do NumPy arrays offer over (nested) Python lists?

Ans:

  1. Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
  2. They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
  3. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
  4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

Q38. Explain the use of decorators.

Ans: Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.

Q39. What is the difference between NumPy and SciPy?

Ans:

  1. In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.
  2. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
  3. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
  4. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

Q40. How do you make 3D plots/visualizations using NumPy/SciPy?

Ans: Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.

Python Programming Certification CourseWatch The Course Preview

Multiple Choice Questions

Q41. Which of the following statements create a dictionary? (Multiple Correct Answers Possible)

a) d = {}

b) d = {“john”:40, “peter”:45}

c) d = {40:”john”, 45:”peter”}

d) d = (40:”john”, 45:”50”)

Answer: b, c & d.

Dictionaries are created by specifying keys and values.

Q42. Which one of these is floor division?

a) /

b) //

c) %

d) None of the mentioned

Answer: b) //

When both of the operands are integer then python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in python is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5

Q43. What is the maximum possible length of an identifier?

a) 31 characters

b) 63 characters

c) 79 characters

d) None of the above

Answer: d) None of the above

Identifiers can be of any length.

Q44. Why are local variable names beginning with an underscore discouraged?

a) they are used to indicate a private variables of a class

b) they confuse the interpreter

c) they are used to indicate global variables

d) they slow down execution

Answer: a) they are used to indicate a private variables of a class

As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.

Q45. Which of the following is an invalid statement?

a) abc = 1,000,000

b) a b c = 1000 2000 3000

c) a,b,c = 1000, 2000, 3000

d) a_b_c = 1,000,000

Answer: b) a b c = 1000 2000 3000

Spaces are not allowed in variable names.

Q46. What is the output of the following?

1

2

3

4

5

6

7

try:

   if '1' != 1:

       raise "someError"

   else:

       print("someError has not occured")

except "someError":

   print ("someError has occured")

a) someError has occured

b) someError has not occured

c) invalid code

d) none of the above

Answer: c) invalid code

A new exception class must inherit from a BaseException. There is no such inheritance here.

Q47. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?

a) Error

b) None

c) 25

d) 2

Answer: c) 25

The index -1 corresponds to the last index in the list.

Q48. To open a file c:scores.txt for writing, we use

a) outfile = open(“c:scores.txt”, “r”)

b) outfile = open(“c:scores.txt”, “w”)

c) outfile = open(file = “c:scores.txt”, “r”)

d) outfile = open(file = “c:scores.txt”, “o”)

Answer: b) The location contains double slashes ( ) and w is used to indicate that file is being written to.

Q49. What is the output of the following?

1

2

3

4

5

6

7

8

f = None

for i in range (5):

   with open("data.txt", "w") as f:

       if i > 2:

           break

print f.closed

a) True

b) False

c) None

d) Error

Answer: a) True

The WITH statement when used with open file guarantees that the file object is closed when the with block exits.

Q50. When will the else part of try-except-else be executed?

a) always

b) when an exception occurs

c) when no exception occurs

d) when an exception occurs in to except block

Answer: c) when no exception occurs

 

Java Interview Q&A

Java Interview Questions

  1. What is Java?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

  1. Mention some features of Java?

Some of the features which play important role in the popularity of java are as follows:

  • Simple: Java is easy to learn. Eventhough Java is based on C++ , it was developed by eliminating poor programming practices of C++.
  • Object-Oriented: Java is a object oriented programming language. Everything in Java is an Object.
  • Portable: Java run time environment uses a bytecode verification process to make sure that code loaded over the network doesn’t violate Java security constraints.
  • Platform independent: Java is platform independent. Java is a write once, run anywhere language. Without any modifications, we can use a program in different platforms.
  • Secured: Java is well known for its security. It delivers virus free systems.
  • High Performance: Java enables high performance with the use of JIT (Just-In-Time) compilers
  • Multithreaded: Java Multithreaded features allows us to write programs that can perform many tasks simulatenously. Multithreading concept of Java shares a common memory area. It doesn’t occupy memory for each thread.
  1. What is the difference between Declaration and Definition in Java?

Declaration: If you just declare a class or method/function or variable without mentioning anything about what that class or method/function or variable looks like is called as declaration in Java.

Definition: If you define how a class or method/function or variable is implemented then it is called definition in Java.

When we create an interface or abstract class, we simply declare a method/function but not define it.

For clear understanding, check the below image

  1. What is an Object in Java?

An object is an instance of a class. Objects have state (variables) and behavior (methods).

Example: A dog is an object of Animal class. The dog has its states such as color, name, breed, and behaviors such as barking, eating, wagging her tail.

public class MyClass{ //Class name (MyClass) declaration public static void main(String[] args){ MyClass obj = new MyClass(); //Object Creation } }

1

2

3

4

5

public class MyClass{    //Class name (MyClass) declaration

   public static void main(String[] args){

       MyClass obj = new MyClass(); //Object Creation

   }

}

  1. What is a Class in Java?

A class can be defined as a collection of objects. It is the blueprint or template that describes the state and behavior of an object.

public class MyClass{ //Class name (MyClass) declaration int a = 9; // Variable declaration int b = 99; public void myMethod(){ //Method (myMethod) declaration int sum=a+b; } }

1

2

3

4

5

6

7

public class MyClass{    //Class name (MyClass) declaration

int a = 9;   // Variable declaration

int b = 99;

   public void myMethod(){ //Method (myMethod) declaration

       int sum=a+b;

   }

}

  1. What is Constructor in Java?

Constructor in Java is used in the creation of an Object that is an instance of a Class. Constructor name should be same as class name. It looks like a method but its not a method. It wont return any value. We have seen that methods may return a value. If there is no constructor in a class, then compiler automatically creates a default constructor.

  1. What is Local Variable and Instance Variable?

Local Variable:

Local variable is a variable which we declare inside a Method. A method will often store its temporary state in local variables.

Instance Variable (Non-static):

Instance variable is a variable which is declared inside a Class but outside a Method. We don’t declare this variable as Static because these variables are non-static variables.

Read more about Variables in Java here

  1. What are the OOPs concepts?

OOPS Stands for Object Oriented Programming System. It includes Abstraction, Encapsulation, Inheritance, Polymorphism, Interface etc.,

Read more on OOPs concept in Java

  1. What is Inheritance in Java?

Inheritance is a process where one class inherits the properties of another class. Read more here

  1. What is Polymorphism?

Polymorphism allows us to perform a task in multiple ways. Let’s break the word Polymorphism and see it, ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’. Read more here

Assume we have four students and we asked them to draw a shape. All the four may draw different shapes like Circle, Triangle, and Rectangle.

  1. What are the types of Polymorphism?

There are two types of Polymorphism in Java

  1. Compile time polymorphism (Static binding) – Method overloading
  2. Runtime polymorphism (Dynamic binding) – Method overriding

We can perform polymorphism by ‘Method Overloading’ and ‘Method Overriding’

  1. What is Method Overloading?

A class having multiple methods with same name but different parameters is called Method Overloading

There are three ways to overload a method.

  • Parameters with different data types
  • Parameters with different sequence of a data types
  • Different number of parameters

Read more on Method Overloading in Java

  1. What is Method Overriding?

Declaring a method in child class which is already present in the parent class is called Method Overriding.

In simple words, overriding means to override the functionality of an existing method.

In this case, if we call the method with child class object, then the child class method is called. To call the parent class method we have to use super keyword.

Read more on Method Overriding

  1. What is Abstraction in Java?

Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the users.

                  

Example: Mobile Phone.

A layman who is using mobile phone doesn’t know how it works internally but he can make phone calls.

  1. What is Abstract Class in Java?

We can easily identify whether a class is an abstract class or not. A class which contains abstract keyword in its declaration then it is an Abstract Class.

Syntax:

abstract class <class-name>{}

1 abstract class <class-name>{}

Points to remember:

  • Abstract classes may or may not include abstract methods
  • If a class is declared abstract then it cannot be instantiated.
  • If a class has abstract method then we have to declare the class as abstract class
  • When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
  1. What is Abstract Method?

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void myMethod();

1 abstract void myMethod();

In order to use an abstract method, you need to override that method in sub class.

  1. What is Interface in Java?

An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract. We can achieve 100% abstraction and multiple inheritance in Java with Interface. Read more on Interface in Java.

  1. What is Encapsulation in Java?

Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class. Read more on Encapsulation in Java

  1. Write a program to print the pattern given below

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

1

2

3

4

5

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Here is the program to print the pattern mentioned above

package software Testing Material; public class NumberPattern {     public static void main(String[] args) {         for (int x = 1; x <= 5; x++) {             for (int y = 1; y <= x; y++) {             System.out.print(y+" ");             }         System.out.println();         }     }    }

1

2

3

4

5

6

7

8

9

10

11

12

13

package softwareTestingMaterial;

public class NumberPattern {

public static void main(String[] args) {

for (int x = 1; x <= 5; x++) {

for (int y = 1; y <= x; y++) {

System.out.print(y+" ");

}

System.out.println();

}

}

}

  1. Write a program to print Fibonacci Series up to count 10.

package software Testing Material; public class FibonacciSeries {         public static void main(String args[]) {         int a = 0, b = 1, c, i, count = 10;         // To print 0 and 1         System.out.print(a + " " + b);         // loop starts from 2. We have already printed 0 and 1 in the previous step         for (i = 2; i < count; i++) {             c = a + b;             System.out.print(" " + c);             a = b;             b = c;         }     } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

package softwareTestingMaterial;

public class FibonacciSeries {

public static void main(String args[]) {

int a = 0, b = 1, c, i, count = 10;

// To print 0 and 1

System.out.print(a + " " + b);

// loop starts from 2. We have already printed 0 and 1 in the previous step

for (i = 2; i < count; i++) {

c = a + b;

System.out.print(" " + c);

a = b;

b = c;

}

}

}

  1. How to reverse a String in Java?

package softwareTestingMaterial; public class ReverseString {         public static void main(String[] args) {     // Using StringBuffer class     StringBuffer a = new StringBuffer("Software Testing Material");     // use reverse() method to reverse string     System.out.println(a.reverse());     }     }

1

2

3

4

5

6

7

8

9

10

11

12

package softwareTestingMaterial;

public class ReverseString {

public static void main(String[] args) {

// Using StringBuffer class

StringBuffer a = new StringBuffer("Software Testing Material");

// use reverse() method to reverse string

System.out.println(a.reverse());

}

}

Another method:

package softwareTestingMaterial; public class ReverseString {         public static void main(String[] args) {         String input="Software Testing Material";         StringBuilder input1 = new StringBuilder();         input1.append(input);         input1=input1.reverse();         for (int i=0;i<input1.length();i++)         System.out.print(input1.charAt(i));     }     }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package softwareTestingMaterial;

public class ReverseString {

public static void main(String[] args) {

String input="Software Testing Material";

StringBuilder input1 = new StringBuilder();

input1.append(input);

input1=input1.reverse();

for (int i=0;i<input1.length();i++)

System.out.print(input1.charAt(i));

}

}

  1. How To Find The Largest Value From The Given Array.

package softwareTestingMaterial; public class LargestValue {     public static void main(String[] args){         int[] arr={28,3,15,9,17,4,23,2};         int val=arr[0];         for(int i=0; i<arr.length; i++){             if(arr[i] > val){                 val=arr[i];             }         }         System.out.println("Largest value in the Given Array is "+ val);     } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package softwareTestingMaterial;

public class LargestValue {

public static void main(String[] args){

int[] arr={28,3,15,9,17,4,23,2};

int val=arr[0];

for(int i=0; i<arr.length; i++){

if(arr[i] > val){

val=arr[i];

}

}

System.out.println("Largest value in the Given Array is "+ val);

}

}

  1. How to display all the prime numbers between 1 and 100

The number which is only divisible by 1 and itself is known as a prime number. For example 2, 3, 5, 7, 11… are prime numbers.

package softwareTestingMaterial; public class PrimeNumbersOneToHundred { public static void main (String[] args){        int i =0; int num =0; String primeNumbers = ""; for (i = 1; i <= 100; i++){             int counter=0;     for(num =i; num>=1; num--){ if(i%num==0){     counter = counter + 1; } }         if (counter ==2){         primeNumbers = primeNumbers + i + " ";         }    }    System.out.println("Prime numbers from 1 to 100 are :"); System.out.println(primeNumbers); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package softwareTestingMaterial;

public class PrimeNumbersOneToHundred {

  public static void main (String[] args){

      int i =0;

      int num =0;

      String  primeNumbers = "";

      for (i = 1; i <= 100; i++){        

         int counter=0;   

         for(num =i; num>=1; num--){

            if(i%num==0){

            counter = counter + 1;

            }

         }

 if (counter ==2){

    primeNumbers = primeNumbers + i + " ";

 }

      }

      System.out.println("Prime numbers from 1 to 100 are :");

      System.out.println(primeNumbers);

  }

}

  1. How to display all the prime numbers between 1 and n (n is the number, get the input from user)

package softwareTestingMaterial; import java.util.Scanner; public class PrimeNumbersOneToN { public static void main (String[] args){        Scanner scanner = new Scanner(System.in); int i =0; int num =0; String primeNumbers = ""; System.out.println("Enter the value of n :"); int n = scanner.nextInt(); scanner.close(); for (i = 1; i <= n; i++)     {                 int counter=0;         for(num =i; num>=1; num--) {     if(i%num==0)     {         counter = counter + 1;     }     }     if (counter ==2)     {     primeNumbers = primeNumbers + i + " ";     }    }    System.out.println("Prime numbers from 1 to n are :"); System.out.println(primeNumbers); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

package softwareTestingMaterial;

import java.util.Scanner;

public class PrimeNumbersOneToN {

  public static void main (String[] args){

     Scanner scanner = new Scanner(System.in);

     int i =0;

     int num =0;

     String  primeNumbers = "";

     System.out.println("Enter the value of n :");

     int n = scanner.nextInt();

     scanner.close();

     for (i = 1; i <= n; i++)       

     {

        int counter=0;   

        for(num =i; num>=1; num--)

        {

   if(i%num==0)

   {

counter = counter + 1;

   }

}

if (counter ==2)

{

   primeNumbers = primeNumbers + i + " ";

}

     }

     System.out.println("Prime numbers from 1 to n are :");

     System.out.println(primeNumbers);

  }

}

  1. How to find the given number is a prime number or not by getting input from the user

package softwareTestingMaterial; import java.util.Scanner; public class PrimeNumberVerification { public static void main(String args[]) { int i, j, flag = 0; System.out.print("Enter any number which you want to verify whether it is a prime number or not :"); Scanner s = new Scanner(System.in); j = s.nextInt(); for( i = 2; i < j; i++){ if(j % i == 0){ flag = 0; break; } else { flag = 1; } } if(flag == 1){ System.out.println(j+" is a prime number."); } else{ System.out.println(+j+" is not a prime number."); } } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

package softwareTestingMaterial;

import java.util.Scanner;

public class PrimeNumberVerification {

   public static void main(String args[])

   {    

       int i, j, flag = 0;

       System.out.print("Enter any number which you want to verify whether it is a prime number or not :");

       Scanner s = new Scanner(System.in);

       j = s.nextInt();

       for( i = 2; i < j; i++){

           if(j % i == 0){

               flag = 0;

               break;

           }

           else

           {

               flag = 1;

           }

        }

        if(flag == 1){

            System.out.println(j+" is a prime number.");

        }

        else{

            System.out.println(+j+" is not a prime number.");

        }          

   }

}

  1. Write a program to print Fibonacci Series

Method 1:

package softwareTestingMaterial; public class FibonacciSeries {         public static void main(String args[]) {         int a = 0, b = 1, c, i, count = 10;         // To print 0 and 1         System.out.print(a + " " + b);         // loop starts from 2. We have already printed 0 and 1 in the previous step         for (i = 2; i < count; i++) {             c = a + b;             System.out.print(" " + c);             a = b;             b = c;         }     } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

package softwareTestingMaterial;

public class FibonacciSeries {

public static void main(String args[]) {

int a = 0, b = 1, c, i, count = 10;

// To print 0 and 1

System.out.print(a + " " + b);

// loop starts from 2. We have already printed 0 and 1 in the previous step

for (i = 2; i < count; i++) {

c = a + b;

System.out.print(" " + c);

a = b;

b = c;

}

}

}

Method 2:

package softwareTestingMaterial; import java.util.Scanner; public class FibonacciSeriesOne {     public static void main(String[] args){         System.out.println("Enter Iteration to print Fibonacci Series");         FibonacciCheck.checkFibonacci(new Scanner(System.in).nextInt());     } } class FibonacciCheck {     public static void checkFibonacci(int number){         int first=0,second=1;         int third=0;         int i=1;         System.out.print("Fibonacci Series upto: "+number+" is ");         System.out.print(first+","+second+",");         while(i<=number){             third=first+second;             System.out.print(third+",");             first=second;             second=third;             ++i;         }     } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package softwareTestingMaterial;

import java.util.Scanner;

public class FibonacciSeriesOne {

public static void main(String[] args){

System.out.println("Enter Iteration to print Fibonacci Series");

FibonacciCheck.checkFibonacci(new Scanner(System.in).nextInt());

}

}

class FibonacciCheck {

public static void checkFibonacci(int number){

int first=0,second=1;

int third=0;

int i=1;

System.out.print("Fibonacci Series upto: "+number+" is ");

System.out.print(first+","+second+",");

while(i<=number){

third=first+second;

System.out.print(third+",");

first=second;

second=third;

++i;

}

}

}

  1. Difference between Array and ArrayList?
Array ArrayList
Array is static ArrayList is dynamic
Size of the array should be given at the time of array declaration. We cannot change the size of array after creating it Size of the array may not be required. It changest the size dynamically. Capacity of ArrayList increases automatically whenever we add elements to an ArrayList
Array can contain both primitive data types as well as objects ArrayList cannot contain primitive data types. It contains only objects
Arrays are multidimensional ArrayList is always single dimension
  1. Difference between ArrayList and HashSet in Java?
ArrayList HashSet
ArrayList implements List interface HashSet implements Set interface
ArrayList allows duplicates HashSet doesn’t allow duplicates
ArrayList is an ordered collection and maintains insertion order of elements HashSet is an unordered collection and doesn’t maintain insertion order
ArrayList is backed by an Array HashSet is backed by an HashMap instance
ArrayList is an index based HashSet is object based
In ArrayList, we can retrive object by calling get() method or remove object by calling remove() method In HashSet, we can’t achieve get() method

Learn more on Array and ArrayList with sample programs

  1. What are the different access modifiers available in Java?

Access modifiers are subdivided into four types such as Default, Public, Private, Protected

default: The scope of default access modifier is limited to the package only. If we do not mention any access modifier, then it acts like a default access modifier.

private: The scope of private access modifier is only within the classes.

Note: Class or Interface cannot be declared as private

protected: The scope of protected access modifier is within a package and also outside the package through inheritance only.

Note: Class cannot be declared as protected

public: The scope of public access modifier is everywhere. It has no restrictions. Data members, methods and classes that declared public can be accessed from anywhere.

 

  1. Difference between static binding and dynamic binding?
  2. Static binding is also known as early binding whereas dynamic binding is also known as late binding.
  3. Determining the type of an object at compile time is Static binding whereas determining the type of an object at run time is dynamic binding
  4. Java uses static binding for overloaded methods and dynamic binding for overridden methods.

To know more about this you have to go through Method Overloading and Method Overriding.

  1. Difference between Abstract Class and Interface?
ABSTRACT CLASS INTERFACE
To declare Abstract class we have to use abstract keyword To declare Interface we have to use interface keyword
In an Abstract class keyword abstract is mandatory to declare a method as an abstract In an Interface keyword abstract is optional to declare a method as an abstract. Compiler treats all the methods as abstract by default
An abstract class contains both abstract methods and concrete methods(method with body) An interface can have only abstract methods
An abstract class provides partial abstraction An interface provides fully abstraction
An abstract class can have public and protected abstract methods An interface can have only public abstract methods
An abstract class can have static, final or static final variables with any access modifiers An interface can have only public static final variables
An abstract class can extend one class or one abstract class An interface can extend any number of interfaces
Abstract class doesn't support multiple inheritance Interface supports multiple inheritance
  1. What is Multiple Inheritance?

If a class implements multiple interfaces, or an interface extends multiple interfaces then it is known as multiple inheritance.

We will update this post “Java Interview Questions For Selenium Testers” ASAP. Keep visiting.

If you like this post, share it with your friends.

 

C- Program Language Interview Questions

C Questions

1. What does static variable mean?
2. What is a pointer?
3. What are the uses of a pointer?
4. What is a structure?
5. What is a union?
6. What are the differences between structures and union?
7. What are the differences between structures and arrays?
8. In header files whether functions are declared or defined?
9. What are the differences between malloc () and calloc ()?
10. What are macros? What are its advantages and disadvantages?
11. Difference between pass by reference and pass by
12. What is static identifier?
13. Where is the auto variables stored?
14. Where does global, static, and local, register
15. Difference between arrays and linked list?
16. What are enumerations?
17. Describe about storage allocation and scope of
18. What are register variables? What are the advantages
19. What is the use of typedef?
20. Can we specify variable field width in a scanf()
21. Out of fgets() and gets() which function is safe to use and why?
22. Difference between strdup and strcpy?
23. What is recursion?
24. Differentiate between a for loop and a while loop? What are it uses?
25. What is storage class.What are the different storage classes in C?
26. What the advantages of using Unions?
27. What is the difference between Strings and Arrays?
28. What is a far pointer? where we use it?
29. What is a huge pointer?
30. What is a normalized pointer ,how do we normalize a pointer?
31. What is near pointer.
32. In C, why is the void pointer useful? When would you use it?
33. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
34. Are pointers integer ?
35. What does the error ‘Null Pointer Assignment’ means and what causes this error?
36. What is generic pointer in C?
37. Are the expressions arr and &arr same for an array of integers?
38. How pointer variables are initialized ?
39. What is static memory allocation ?
40. What is dynamic memory allocation?
41. What is the purpose of realloc ?
42. What is pointer to a pointer.
43. What is an array of pointers ?
44. Difference between linker and linkage ?
45. Is it possible to have negative index in an array?
46. Why is it necessary to give the size of an array in an array declaration ?
47. What modular programming ?
48. What is a function ?
49. What is an argument ?
50. What are built in functions ?
51. Difference between formal argument and actual argument ?
52. Is it possible to have more than one main() function in a C program ?
53. What is the difference between an enumeration and a set of pre-processor # defines?
54. How are Structure passing and returning implemented by the complier?
55. What is the similarity between a Structure, Union and enumeration?
56. Can a Structure contain a Pointer to itself?
57. How can we read/write Structures from/to data files?
58. Write a program which employs Recursion ?
59. Write a program which uses Command Line Arguments?
60. Difference between array and pointer ?
61. What do the ‘c’ and ‘v’ in argc and argv stand for?
62. What are C tokens ?
63. What are C identifiers?
64. Difference between syntax vs logical error?
65. What is preincrement and post increment ?
66. Write a program to interchange 2 variables without using the third one.
67. What is the maximum combined length of command line arguments including the space between adjacent arguments?
68. What are bit fields? What is the use of bit fields in a Structure declaration?
69. What is a preprocessor, What are the advantages of preprocessor ?
70. What are the facilities provided by preprocessor ?
71. What are the two forms of #include directive ?
72. How would you use the functions randomize() and random()?
73. What do the functions atoi(), itoa() and gcvt() do?
74. How would you use the functions fseek(), freed(), fwrite() and ftell()?
75. What is the difference between the functions memmove() and memcpy()?
76. What is a file ?
77. What are the types of file?
78. What is a stream ?
79. What is meant by file opening ?
81. What is a file pointer ?
82. How is fopen()used ?
83. How is a file closed ?
84. What is a random access file ?
85. What is the purpose of ftell ?
86. What is the purpose of rewind() ?
87. Difference between a array name and a pointer variable ?
88. Represent a two-dimensional array using pointer ?
89. Difference between an array of pointers and a pointer to an array ?
90. Can we use any name in place of argv and argc as command line arguments ?
91. What are the pointer declarations used in C?
92. Differentiate between a constant pointer and pointer to a constant ?
93. Is the allocated space within a function automatically deallocated when the function returns?
94. Discuss on pointer arithmetic?
95. What are the invalid pointer arithmetic ?
96. What are the advantages of using array of pointers to string instead of an array of strings?
97. Are the expressions *ptr ++ and ++ *ptr same ?
98. What would be the equivalent pointer expression foe referring the same element as a[p][q][r][s] ?
99. Are the variables argc and argv are always local to main ?
100. Can main () be called recursively?
101. Can we initialize unions?
102. What’s the difference between these two declarations?
103. Why doesn’t this code: a[i] = i++; work?
104. Why doesn’t struct x { … };x thestruct; work?
105. Why can’t we compare structures?
106. How are structure passing and returning implemented?

 

C++ Program Language Interview Questions
      1. Question 1. What Is The Difference Between C And C++ ?

        Answer :

        • C is a procedural language on the other hand c++ is an object oriented language.
        • C follows top down approach, c++ follows bottom up approach.
        • C is a low level language, c++ is a middle level language.
        • Input and putput functions differs in the two languages, c uses printf and scanf whereas c++ uses >> and << as input and output operators.
        • C++ can be broken down to solve real world problems which is not the case in c.

         

      2. Question 2. What Is The Difference Between Declaration And Definition ?

        Answer :

        There are basically two differences between declaration and definition : 

        • In declaration no space is reserved for the variable, declaration only tells about the 'type' of the variable we are using or we will be using int he program.
        • Definition on the other hand reserves the sapce for the variable and some initial value is given to it.
        • Another major difference is that redeclaration is not an error whereas redefinition is an error,
        • In simple words, when we declare no space is reserved for the variable and we can redeclare it in the program
        • On the other hand, when we define a variable some sapce is reserved for it to hold values plus some initial value is also given to it, apart from it we cannot give another definition to the variable, i.e. we cannot define it again.

        Example: 

        extern int x -> is a declaration whereas int y is definition.

         

      3. Question 3. If You Want To Share Several Functions Or Variables In Several Files Maintaining The Consistency How Would You Share It?

        Answer :

        To maintain the consistency between several files firstly place each definition in '.c' file than using external declarations put it in '.h' file after it is included .h file we can use it in several files using #include as it will be in one of the header files, thus to maintain the consistency we can make our own header file and include it where ever needed.

         

      1. Question 4. What Do You Mean By Translation Unit?

        Answer :

        A Translation Unit is a set of source files that is seen by the compiler and it translate it as one unit which is generally.file and all the header files mentioned in #include directives.

        When a C preprocessor expands the source file with all the header files the result is the preprocessing translation unit which when further processed translates the preprocessing translation unit into translation unit, further with the help of this translation unit compiler forms the object file and ultimately forms an executable program.

         

      2. Question 5. Describe Linkages And Types Of Linkages?

        Answer :

        When we declare identifiers within the same scope or in the different scopes they can be made to refer the same object or function with the help of likages. 

        There are three types of linkages: 

        • External linkage 
        • Internal linkage 
        • None linkage

        EXternal Linkages means 'global, non-static' functions or variable.

        Example: extern int a1

        Internal Linkages means static variable and functions. Example: static int a2

        None Linkages means local variables.

        Example : int a3

         

      3. Question 6. Keeping In Mind The Efficiency, Which One Between If-else And Switch Is More Efficient?

        Answer :

        • Between if-else chain and switch statements, as far as efficiency is concerned it is hard to say that which one is more efficient because both of them posses hardly any difference in terms of efficiency. 
        • Switch can ne converted into if else chain internally by the compiler.
        • Switch statements are compact way of writting a jump table whereas if-else is a long way of writting conditions.
        • Between if-esle and switch statements, switch cases are prefered to be used in the programming as it is a compact and cleaner way of writting conditions in the program.

         

      1. Question 7. What Are Structures And Unions?

        Answer :

        While handling real world problems we come across situations when we want to use different data type as one, C allows the user to define it own data type known as structures and unions.Structures and unions gathers together different atoms of informations that comprise a given entity.

         

      2. Question 8. What Is The Difference Between Structures And Unions?

        Answer :

        • Conceptually structures and unions are same, the differnce between them lies in their 'Memory Management' or in simple words the memory required by them.
        • Elements in structures are stored in contiguous blocks, where as in unions the memory is allocated in such a way that the same memory allocated for one variable serves as its memory at one occassion and as memory for another varioable at some other occassion. 
        • Therefore, the basic difference lies in the way mrmory is allocated to both structures and unions.

         

      3. Question 9. What Do You Mean By Enumerated Data Type?

        Answer :

        Enumerated Data type helps the user in defining its own data type and also gives the user an opportunity to define what values this type can take.

        The use of Enumerated Data Type maily lie when the program get more complicated or more number of programers are workin on it as it makes the program listings more readable.

         

      1. Question 10. What Are Preprocessor Directives In C?

        Answer :

        The Preprocessor processes the source program before it is passed to the compiler. The features that preprocessor offers are known as Prepsocessor Directives.

        Preprocessing directives are lines in your program that start with `#'. The `#' is followed by an identifier that is the directive name. For example, `#define' is the directive that defnes a macro. Whitespace is also allowed before and after the `#'. A preprocessing directive cannot be more than one line in normal circumstances. Some directive names require arguments.View answers in details

         

      2. Question 11. How C Functions Prevents Rework And Therefore Saves The Programmers Time As Well As Length Of The Code ?

        Answer :

        As we know that c allows us to make functions and cal them where ever needed, it prevents rework by calling the same function again and again where ever requires intead for example if we make a funtion that adds two numbers, it can be called anywhere in the program where ever the addintion is needed and we do not need to code again for adding any number. 

        It also shortens the length of the program as we do not need to code again the same thing for next time we can simple call the funtion and use it whenever needed.

         

      3. Question 12. Keyword Mean In Declaration?

        Answer :

        This keyword indicated that the function or the variable is implemented externally and it emphasizes that the variable ot the function exits external to the file or function.

        We use this keyword when we want to make anything global in the project, it does not lie within any function.

         

      1. Question 13. Can Union Be Self Referenced?

        Answer :

        No, Union cannot be self referenced because it shares a single memory for all of its data members.View answers in details

         

      2. Question 14. Define Pointers?

        Answer :

        • Pointes are special type of variables that are used to store the memory address of the other variables.
        • Pointers are declared normallt as other variables withe diffrence of * that is present in front of the pointer identifier.
        • There are two operators that are used with the pointers one is '&' and another one is '*'.
        • & is known as address of operator and * is known as dereferncing operator, both are prefix unary operators.

         

      3. Question 15. Which Format Specifier Is Used For Printing A Pointer Value?

        Answer :

        • %p is used to display the corresponding argument that is a pointer.
        • %x can also be used to print values in hexadecimal form.

         

    1. Question 16. What Is The Use Of 'auto' Keyword ?

      Answer :

      • The auto keyword declares a local variable whose scope remains within the block of code, it is a variable with the local scope.
      • When we declare a variable with the auto keyword it specify that it belongs to an auto storage class.
      • These variables are visible only within the bolck in which they are declared.
      • These types of variables are not initialised automatically instead need to be initialised xplicitly.

       

    2. Question 17. What Is The Use Of Register Keyword With The Variables?

      Answer :

      • Register keyword signifies that of possible to store variable in the register than store it in register. 
      • Variables are usually stored in stacks and are passed to and fro to processor whenever required.
      • Also register keyword when used redused code size which is an important thing in embeded system.

       

    3. Question 18. What Do You Mean By Global Variables?

      Answer :

      These are the variables which remains visible throughout the program and are not recreated when they are recalled.

      These types are by default initialised to zero and allocated memory on Data Segment.View answers in details

       

    4. Question 19. What Do You Mean By Static Variables?

      Answer :

      Static is an access qualifier that limits the scope of the variable but causes the variable to exist for the lifetime of the program. This means a static variable is one that is not seen outside the function in which it is declared as its scopeis limited to the block of code in which it has been created but its lifespan remains until the program terminates.

      The value of such a variable will remain and may be seen even after calls to a function also the declaration statement of such type of a variable inside a function is executed only once.

       

    5. Question 20. What Is The Difference Between Global Variables And Static Variables?

      Answer :

      • The scope of the variable describes that the variable is accessible at certain point in the program or not.
      • The difference between global variables and static variables lies in this concept only. 
      • The scope of the global variables remains through out the program also the life span of these variables is through out the program.
      • The scope of the static Variables remains within the block of code in which they are created but the life span remains through out the program.
      • Thus, the main difference is between the scope of both type of variables.

       

    6. Question 21. What Is The Difference Between Global Variables And Local Variable?

      Answer :

      • First, Global variables are the variables which can be accessed from anywhere through out the program whereas local variables are those which can only be accessed within the block of code in which they are created.
      • Second, global variables are visible throughout the program whereas local variables are not known to the other functions in the programs i.e. they are visible within the block of code in which they are created.
      • Third, global variables are allocated memory on Data Segament whereas local variables are allocated memory on the stack.

       

    7. Question 22. What Do You Mean By Volatile Variable?

      Answer :

      Variables prefixed with the keyword volatile acts as a data type qualifier. The volatile keyword attempts to alter the default way in which the variables are stored and the way the compiler handles the variables.

      It is a kind of instruction to the optimizer to not to optimize the varabli during compilation.

       

    8. Question 23. What Is The Prototype Of Printf Function?

      Answer :

      Prototype of printf function is:

      int printf( const char *format ,?)

      In this the Second parameter: '?' (Three continuous dots) are known as called ellipsis which indicates the variable number of arguments.

       

    9. Question 24. Define Macro?

      Answer :

      • Macros are the identifiers that represent statements or expressions in other words macros are fragment of code which is been given a name. #define directive is used to dedine a macro.
      • Example, we have define a macro i.e SQUARE(x) x*x. 
      • Here the macro determines the square of the given number. Macro Declaration: #define name text.

       

    10. Question 25. What Is The Disadvantage Of Using A Macro?

      Answer :

      The major disadvantage associated with the macro is :

      When a macro is invoked no type checking is performed.Therefore it is important to declare a macro coreectly so that it gives a correct answer whenever it is called inside the program.

       

    11. Question 26. What Is A Void Pointer?

      Answer :

      When we declare a variable as a pointer to a variable of type void, it is known as void pointer. Another name for it is generic pointer.

      In general we cannot have a void type variable,but if the variable is of void type it do not point to any data and due to this it cannot be de-referenced.

       

    12. Question 27. What Is A Unnitialised Pointer?

      Answer :

      When we create a pointer the memory to the pointer is allocated but the contents or value that memory has to hold remains untouched. Unitialised pointers are those pointers which do not hold any initial value.

      Example: int *p; is said to be an unitialise pointer, it is recomended to initialise the pointer before actually using it as it an error.

       

    13. Question 28. What Is Dangling Pointer?

      Answer :

      These are the pointers that do not point to any object of appropriate type. These are special cases of memory vialation as they do not point to any appropraite type.These arises when some object is deleted from the memory or when an object is deallocated thus the pointer keeps on pointin to the memory location untill it is modified. Dangling pointers may lead to unpredictable results.

       

    14. Question 29. What Do You Know About Near, Far And Huge Pointer?

      Answer :

      • A near pointer is a 16 bit pointer to an object which is contained in the current segment like code segment, data segment, stack segment and extra segment. It holds only offset address.
      • A far pointer is a 32 bit pointer to an object anywhere in memory. It can only be used when the compiler allocates a segment register, or we can say the compiler must allocate segment register to use far pointers. These pointers hold 16 bit segment and 16 bit offset address.
      • Huge pointers are also far pointers i.e. 32 bit pointer the difference is that the huge pointer can be increased or decreased uniformly between any segments and can have any value from 0 to 1MB.

       

    15. Question 30. What Is Null Pointer?

      Answer :

      NULL pointer is not the unitialised pointer that can point anywhere, the NULL pointers are the one which do not point anywhere that is which do not point to any object or any function.

       

SQL Queries Question & Answers

SET 1 - SQL Queries Question &  Answers

Hello friends! in this post we will see some of the most commonly asked SQL queries in interviews. The questions will start from very basic questions and then move to more complex problems. Consider the below two tables for most of the questions asked here.

 

Table - EmployeeDetails

EmpId FullName ManagerId DateOfJoining
121 John Snow 321 01/31/2014
321 Walter White 986 01/30/2015
421 Kuldeep Rana 876 27/11/2016

Table - EmployeeSalary

EmpId Project Salary
121 P1 8000
321 P2 1000
421 P1 12000

 

SQL Query Interview Questions with Answers


Ques.1. Write a SQL query to fetch the count of employees working in project 'P1'.
Ans. Here, we would be using aggregate function count() with the SQL where clause-

SELECT COUNT(*) FROM EmployeeSalary WHERE Project = 'P1';



Ques.2. Write a SQL query to fetch employee names having salary greater than or equal to 5000 and less than or equal 10000.
Ans. Here, we will use BETWEEN in the 'where' clause to return the empId of the employees with salary satifying the required criteria and then use it as subquery to find the fullName of the employee form EmployeeDetails table.

SELECT FullName 
FROM EmployeeDetails 
WHERE EmpId IN 
(SELECT EmpId FROM EmpolyeeSalary 
WHERE Salary BETWEEN 5000 AND 10000);



Ques.3. Write a SQL query to fetch project-wise count of employees sorted by project's count in descending order.
Ans. The query has two requirements - first to fetch the project-wise count and then to sort the result by that count. For project wise count, we will be using GROUPBY clause and for sorting, we will use ORDER BY clause on the alias of the project-count.

SELECT Project, count(EmpId) EmpProjectCount 
FROM EmployeeSalary 
GROUP BY Project 
ORDER BY EmpProjectCount DESC;



Ques.4. Write a query to fetch only the first name(string before space) from the FullName column of EmployeeDetails table.
Ans. In this question, we are required to first fetch the location of the space character in the FullName field and then extract the first name out of the FullName field. For finding the location we will use LOCATE method in mySQL and CHARINDEX in SQL SERVER and for fetching the string before space, we will use SUBSTRING OR MID method.

mySQL- Using MID

SELECT MID(FullName, 0, LOCATE(' ',FullName)) FROM EmployeeDetails;


SQL Server-Using SUBSTRING

SELECT SUBSTRING(FullName, 0, CHARINDEX(' ',FullName)) FROM EmployeeDetails;


Also, we can use LEFT which returns the left part of a string till specified number of characters.

SELECT LEFT(FullName, CHARINDEX(' ',FullName) - 1) FROM EmployeeDetails;



Ques.5. Write a query to fetch employee names and salary records. Return employee details even if the salary record is not present for the employee.
Ans. Here, we can use left join with EmployeeDetail table on the left side.

SELECT E.FullName, S.Salary  
FROM EmployeeDetails E LEFT JOIN EmployeeSalary S
ON E.EmpId = S.EmpId;



Ques.6. Write a SQL query to fetch all the Employees who are also managers from EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the EmployeeDetails table as two different tables, each for Employee and manager records.

SELECT DISTINCT E.FullName
FROM EmpDetails E
INNER JOIN EmpDetails M
ON E.EmpID = M.ManagerID;



Ques.7. Write a SQL query to fetch all employee records from EmployeeDetails table who have a salary record in EmployeeSalary table.
Ans. Using 'Exists'-

SELECT * FROM EmployeeDetails E 
WHERE EXISTS 
(SELECT * FROM EmployeeSalary S WHERE  E.EmpId = S.EmpId);



Ques.8. Write a SQL query to fetch duplicate records from a table.
Ans. In order to find duplicate records from table we can use GROUP BY on all the fields and then use HAVING clause to return only those fields whose count is greater than 1 i.e. the rows having duplicate records.

SELECT EmpId, Project, Salary, COUNT(*)
FROM EmployeeSalary
GROUP BY EmpId, Project, Salary
HAVING COUNT(*) > 1;



Ques.9. Write a SQL query to remove duplicates from a table without using temporary table.
Ans. Using Group By and Having clause-

DELETE FROM EmployeeSalary  
WHERE EmpId IN (
SELECT EmpId 
FROM EmployeeSalary       
GROUP BY Project, Salary
HAVING COUNT(*) > 1));

 

Using rowId in Oracle-

DELETE FROM EmployeeSalary
WHERE rowid NOT IN
(SELECT MAX(rowid) FROM EmployeeSalary GROUP BY EmpId);



Ques.10. Write a SQL query to fetch only odd rows from table.
Ans. This can be achieved by using Row_number in SQL server-

SELECT E.EmpId, E.Project, E.Salary
FROM (
    SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber
    FROM EmployeeSalary
) E
WHERE E.RowNumber % 2 = 1





Ques.11. Write a SQL query to fetch only even rows from table.
Ans. Using the same Row_Number() and checking that the remainder when divided by 2 is 0-

SELECT E.EmpId, E.Project, E.Salary
FROM (
    SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber
    FROM EmployeeSalary
) E
WHERE E.RowNumber % 2 = 0



Ques.12. Write a SQL query to create a new table with data and structure copied from another table.
Ans. Using SELECT INTO command-

SELECT * INTO newTable FROM EmployeeDetails;



Ques.13. Write a SQL query to create an empty table with same structure as some other table.
Ans. Using SELECT INTO command with False 'WHERE' condition-

SELECT * INTO newTable FROM EmployeeDetails WHERE 1 = 0;

 

This can also done using mySQL 'Like' command with CREATE statement-

CREATE TABLE newTable LIKE EmployeeDetails; 



Ques.14. Write a SQL query to fetch common records between two tables.
Ans. Using INTERSECT-

SELECT * FROM EmployeeSalary
INTERSECT
SELECT * FROM ManagerSalary



Ques.15. Write a SQL query to fetch records that are present in one table but not in another table.
Ans. Using MINUS-

SELECT * FROM EmployeeSalary
MINUS
SELECT * FROM ManagerSalary



Ques.16. Write a SQL query to find current date-time.
Ans. mySQL-

SELECT NOW();

 

SQL Server-

SELECT getdate();

 

Oracle-

SELECT SYSDATE FROM DUAL;



Ques.17. Write a SQL query to fetch all the Employees details from EmployeeDetails table who joined in Year 2016.
Ans. Using BETWEEN for the date range '01-01-2016' AND '31-12-2016'-

SELECT * FROM EmployeeDetails
WHERE DateOfJoining BETWEEN '01-01-2016' AND date '31-12-2016';

 

Also, we can extract year part from the joining date (using YEAR in mySQL)-

SELECT * FROM EmployeeDetails
WHERE YEAR(DateOfJoining) = '2016';



Ques.18. Write a SQL query to fetch top n records?
Ans. In mySQL using LIMIT-

SELECT * FROM EmployeeSalary ORDER BY Salary DESC LIMIT N

 

In SQL server using TOP command-

SELECT TOP N * FROM EmployeeSalary ORDER BY Salary DESC

 

In Oracle using ROWNUM-

SELECT * FROM (SELECT * FROM EmployeeSalary ORDER BY Salary DESC)
WHERE ROWNUM <= 3;




Ques.19. Write SQL query to find the nth highest salary from table.
Ans. Using Top keyword (SQL Server)-

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      )
ORDER BY Salary ASC

 

Using limit clause(mySQL)-

SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT N-1,1;



Ques.20. Write SQL query to find the 3rd highest salary from table without using TOP/limit keyword.
Ans. The below SQL query make use of correlated subquery wherein in order to find the 3rd highest salary the inner query will return the count of till we find that there are two rows that salary greater than other distinct salaries.

SELECT Salary
FROM EmployeeSalary Emp1
WHERE 2 = (
                SELECT COUNT( DISTINCT ( Emp2.Salary ) )
                FROM EmployeeSalary Emp2
                WHERE Emp2.Salary > Emp1.Salary
            )

 

For nth highest salary-

SELECT Salary
FROM EmployeeSalary Emp1
WHERE N-1 = (
                SELECT COUNT( DISTINCT ( Emp2.Salary ) )
                FROM EmployeeSalary Emp2
                WHERE Emp2.Salary > Emp1.Salary
            )

 

 

SET 2 - SQL Queries Question &  Answers

Question #1) What is SQL?

Structured Query Language is a database tool which is used to create and access database to support software application.

Question #2) What are tables in SQL?

The table is a collection of record and its information at a single view.

Question #3) What are different types of statements supported by SQL?

statements supported by SQL

There are 3 types of SQL statements

1) DDL (Data Definition Language): It is used to define the database structure such as tables. It includes three statements such as Create, Alter, and Drop.

Some of the DDL Commands are listed below

  • CREATE: It is used for creating the table.
1 CREATE TABLE&amp;amp;amp;nbsp;table_name
2 column_name1 data_type(size),
3 column_name2 data_type(size),
4 column_name3 data_type(size),
  • ALTER: The ALTER table is used for modifying the existing table object in the database.

ALTER TABLE table_name
ADD column_name datatype

OR

ALTER TABLE table_name

DROP COLUMN column_name

2) DML (Data Manipulation Language): These statements are used to manipulate the data in records. Commonly used DML statements are Insert, Update, and Delete.

The Select statement is used as partial DML statement that is used to select all or relevant records in the table.

3) DCL (Data Control Language): These statements are used to set privileges such as Grant and Revoke database access permission to the specific user.

Question #4) How do we use DISTINCT statement? What is its use?

DISTINCT statement is used with the SELECT statement. If the records contain duplicate values then DISTINCT is used to select different values among duplicate records.

Syntax: SELECT DISTINCT column_name(s)
FROM table_name;

Question #5) What are different Clauses used in SQL?

Clauses used in SQL

  • WHERE Clause: This clause is used to define the condition, extract and display only those records which fulfill the given condition

Syntax: SELECT column_name(s) 
FROM table_name 
WHERE condition;

  • GROUP BY Clause: It is used with SELECT statement to group the result of the executed query using the value specified in it. It matches the value with the column name in tables and groups the end result accordingly.

Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name;

  • HAVING clause: This clause is used in association with GROUP BY clause. It is applied to the each group of result or the entire result as single group and much similar as WHERE clause, the only difference is you cannot use it without GROUP BY clause

Syntax: SELECT column_name(s) 
FROM table_name 
GROUP BY column_name 
HAVING condition;

  • ORDER BY clause: This clause is to define the order of the query output either in ascending (ASC) or in descending (DESC) order. Ascending (ASC) is the default one but descending (DESC) is set explicitly.

Syntax: SELECT column_name(s) 
FROM table_name 
WHERE condition 
ORDER BY column_name ASC|DESC;

  • USING clause: USING clause comes in use while working with SQL Joins. It is used to check equality based on columns when tables are joined. It can be used instead ON clause in Joins.

Syntax: SELECT column_name(s) 
FROM table_name 
JOIN table_name 
USING (column_name);

Question #6) Why do we use SQL constraints? Which constraints we can use while creating database in SQL?

Constraints are used to set the rules for all records in the table. If any constraints get violated then it can abort the action that caused it.

Constraints are defined while creating the database itself with CREATE TABLE statement or even after the table is created once with ALTER TABLE statement.

There are 5 major constraints are used in SQL, such as

  • NOT NULL: That indicates that the column must have some value and cannot be left null
  • UNIQUE: This constraint is used to ensure that each row and column has unique value and no value is being repeated in any other row or column
  • PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE constraints such as on one or the combination of more than one columns to identify the particular record with a unique identity.
  • FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also matches the value in one table with another using Primary Key
  • CHECK: It is used to ensure whether the value in columns fulfills the specified condition

Question #7) What are different JOINS used in SQL?

SQL Joins

There are 4 major types of joins made to use while working on multiple tables in SQL databases

  • INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables when it has at least one column matched

Syntax: SELECT column_name(s) 
FROM table_name1 
INNER JOIN table_name2 
ON column_name1=column_name2;

Example

In this example, we have a table Employee with the following data

Employee table

The second Table is joining

joining

Enter the following SQL statement

1 SELECT Employee.Emp_id, Joining.Joining_Date
2   FROM Employee
3   INNER JOIN Joining
4   ON Employee.Emp_id = Joining.Emp_id
5   ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see

result of innerjoin

Employee and orders tables where there is a matching customer_id value in both the Employee and orders tables

  • LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from a LEFT table and its matched
    rows from a RIGHT table.

Syntax: SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON column_name1=column_name2;

Example

In this example, we have a table Employee with the following data:

Employee table

Second Table is joining

joining 1

Enter the following SQL statement

1 SELECT Employee.Emp_id, Joining.Joining_Date
2 FROM Employee
3 LEFT OUTER JOIN Joining
4 ON Employee.Emp_id = Joining.Emp_id
5 ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see:

result of LEFT OUTER JOIN

  • RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table and its matched rows from a LEFT table.

Syntax: SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON column_name1=column_name2;

Example

In this example, we have a table Employee with the following data

Employee table

The second Table is joining

joining 1

Enter the following SQL statement

1 SELECT Employee.Emp_id, Joining.Joining_Date
2 FROM Employee
3 LEFT OUTER JOIN Joining
4 ON Employee.Emp_id = Joining.Emp_id
5 ORDER BY Employee.Emp_id;

There will be 4 records selected. These are the results that you should see

result of RIGHT OUTER JOIN

  • FULL JOIN (FULL OUTER JOIN): This joins returns all when there is a match either in the RIGHT table or in the LEFT table.

Syntax: SELECT column_name(s)
FROM table_name1
FULL OUTER JOIN table_name2
ON column_name1=column_name2;

Example

In this example, we have a table Employee with the following data:

Employee table

Second Table is joining

joining 1

Enter the following SQL statement:

1 SELECT Employee.Emp_id, Joining.Joining_Date
2 FROM Employee
3 FULL OUTER JOIN Joining
4 ON Employee.Emp_id = Joining.Emp_id
5 ORDER BY Employee.Emp_id;

There will be 8 records selected. These are the results that you should see

result of FULL OUTER JOIN

Question #8) What are transaction and its controls?

A transaction can be defined as the sequence task that is performed on databases in a logical manner to gain certain results. Operations performed like Creating, updating, deleting records in the database comes from transactions.

In simple word, we can say that a transaction means a group of SQL queries executed on database records.

There are 4 transaction controls such as

  • COMMIT: It is used to save all changes made through the transaction
  • ROLLBACK: It is used to roll back the transaction such as all changes made by the transaction are reverted back and database remains as before
  • SET TRANSACTION: Set the name of transaction
  • SAVEPOINT: It is used to set the point from where the transaction is to be rolled back

Question #9) What are properties of the transaction?

      Properties of transaction are known as ACID properties, such as

  • Atomicity: Ensures the completeness of all transactions performed. Checks whether every transaction is completed successfully if not then transaction is aborted at the failure point and the previous transaction is rolled back to its initial state as changes undone
  • Consistency: Ensures that all changes made through successful transaction are reflected properly on database
  • Isolation: Ensures that all transactions are performed independently and changes made by one transaction are not reflected on other
  • Durability: Ensures that the changes made in database with committed transactions persist as it is even after system failure

Question #10) How many Aggregate Functions are available there in SQL?

SQL Aggregate Functions calculates values from multiple columns in a table and returns a single value.

There are 7 aggregate functions we use in SQL

  • AVG(): Returns the average value from specified columns
  • COUNT(): Returns number of table rows
  • MAX(): Returns largest value among the records
  • MIN(): Returns smallest value among the records
  • SUM(): Returns the sum of specified column values
  • FIRST(): Returns the first value
  • LAST(): Returns Last value

Question #11) What are Scalar Functions in SQL?

Scalar Functions are used to return a single value based on the input values. Scalar Functions are as follows

  • UCASE(): Converts the specified field in upper case
  • LCASE(): Converts the specified field in lower case
  • MID(): Extracts and returns character from text field
  • FORMAT(): Specifies the display format
  • LEN(): Specifies the length of text field
  • ROUND(): Rounds up the decimal field value to a number

Question #12) What are triggers?

Triggers in SQL is kind of stored procedures used to create a response to a specific action performed on the table such as Insert, Update or Delete. You can invoke triggers explicitly on the table in the database.

Action and Event are two main components of SQL triggers when certain actions are performed the event occurs in response to that action.

Syntax: CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}
ON table_name [FOR [EACH] {ROW|STATEMENT}]
EXECUTE PROCEDURE functionname {arguments}

Question #13) What is View in SQL?

A View can be defined as a virtual table that contains rows and columns with fields from one or more table.

Syntax: CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Question #14) How we can update the view?

SQL CREATE and REPLACE can be used for updating the view.

Following query syntax is to be executed to update the created view

Syntax: CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Question #15) Explain the working of SQL Privileges?

SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user environments.  The administrator of the database can grant or revoke privileges to or from users of database object like SELECT, INSERT, UPDATE, DELETE, ALL etc.

GRANT Command: This command is used provide database access to user apart from an administrator.

Syntax: GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];

In above syntax WITH GRANT OPTIONS indicates that the user can grant the access to another user too.

REVOKE Command: This command is used provide database deny or remove access to database objects.

Syntax: REVOKE privilege_name
ON object_name
FROM {user_name|PUBLIC|role_name};

Question #16) How many types of Privileges are available in SQL?

There are two types of privileges used in SQL, such as

  • System Privilege: System privileges deal with an object of a particular type and specifies the right to perform one or more actions on it which include Admin allows a user to perform administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
  • Object Privilege: This allows to perform actions on an object or object of another user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE, INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.

Question #17) What is SQL Injection?

SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of database such that once it is executed the database is opened for an attacker. This technique is usually used for attacking Data-Driven Applications to have an access to sensitive data and perform administrative tasks on databases.

For Example: SELECT column_name(s) FROM table_name WHERE condition;

Question #18) What is SQL Sandbox in SQL Server?

SQL Sandbox is the safe place in SQL Server Environment where untrusted scripts are executed. There are 3 types of SQL sandbox, such as

  • Safe Access Sandbox: Here a user can perform SQL operations such as creating stored procedures, triggers etc. but cannot have access to the memory and cannot create files.
  • External Access Sandbox: User can have access to files without having a right to manipulate the memory allocation.
  • Unsafe Access Sandbox: This contains untrusted codes where a user can have access to memory.

Question #19) What is the difference between SQL and PL/SQL?

SQL is a structured query language to create and access databases whereas PL/SQL comes with procedural concepts of programming languages.

Question #20) What is the difference between SQL and MySQL?

SQL is a structured query language that is used for manipulating and accessing the relational database, on the other hand, MySQL itself is a relational database that uses SQL as the standard database language.

Question #21) What is the use of NVL function?

NVL function is used to convert the null value to its actual value.

Question #22) What is the Cartesian product of table?

The output of Cross Join is called as a Cartesian product. It returns rows combining each row from the first table with each row of the second table. For Example, if we join two tables having 15 and 20 columns the Cartesian product of two tables will be 15×20=300 Rows.

Question #23) What do you mean by Subquery?

Query within another query is called as Subquery. A subquery is called inner query which returns output that is to be used by another query.

Question #24) How many row comparison operators are used while working with a subquery?

There are 3-row comparison operators which are used in subqueries such as IN, ANY and ALL.

Question #25) What is the difference between clustered and non-clustered indexes?

  • One table can have only one clustered index but multiple nonclustered indexes.
  • Clustered indexes can be read rapidly rather than non-clustered indexes.
  • Clustered indexes store data physically in the table or view and non-clustered indexes do not store data in table as it has separate structure from data row

Question #26) What is the difference between DELETE and TRUNCATE?

  • The basic difference in both is DELETE is DML command and TRUNCATE is DDL
  • DELETE is used to delete a specific row from the table whereas TRUNCATE is used to remove all rows from the table
  • We can use DELETE with WHERE clause but cannot use TRUNCATE with it

Question #27) What is the difference between DROP and TRUNCATE?

TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes the entire table from the database and it cannot be retrieved back.

Question #28) How to write a query to show the details of a student from Students table whose
name starts with K?

SELECT * FROM Student WHERE Student_Name like ‘%K’;

Here ‘like’ operator is used for pattern matching.

Question #29) What is the difference between Nested Subquery and Correlated Subquery?

Subquery within another subquery is called as Nested Subquery.  If the output of a subquery is depending on column values of the parent query table then the query is called Correlated Subquery.

SELECT adminid(SELEC Firstname+’ ‘+Lastname  FROM Employee WHERE
empid=emp. adminid)AS EmpAdminId FROM Employee

This query gets details of an employee from Employee table.

Question #30) What is Normalization? How many Normalization forms are there?

Normalization is used to organize the data in such manner that data redundancy will never occur in the database and avoid insert, update and delete anomalies.

There are 5 forms of Normalization

  • First Normal Form (1NF): It removes all duplicate columns from the table. Creates table for related data and identifies unique column values
  • First Normal Form (2NF): Follows 1NF and creates and places data subsets in an individual table and defines relationship between tables using primary key
  • Third Normal Form (3NF): Follows 2NF and removes those columns which are not related through primary key
  • Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies. 4NF also known as BCNF

Question #31) What is Relationship? How many types of Relationship are there?

The relationship can be defined as the connection between more than one tables in the database.

There are 4 types of relationships

  • One to One Relationship
  • Many to One Relationship
  • Many to Many Relationship
  • One to Many Relationship

Question #32) What do you mean by Stored Procedures? How do we use it?

A stored procedure is a collection of SQL statements which can be used as a function to access the database. We can create these stored procedures previously before using it and can execute these them wherever we require and also apply some conditional logic to it. Stored procedures are also used to reduce network traffic and improve the performance.

Syntax: CREATE Procedure Procedure_Name
(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END

Question #33) State some properties of Relational databases?

  • In relational databases, each column should have a unique name
  • Sequence of rows and columns in relational databases are insignificant
  • All values are atomic and each row is unique

Question #34) What are Nested Triggers?

Triggers may implement data modification logic by using INSERT, UPDATE, and DELETE statement. These triggers that contain data modification logic and find other triggers for data modification are called Nested Triggers.

Question #35) What is Cursor?

A cursor is a database object which is used to manipulate data in a row-to-row manner.

Cursor follows steps as given below

  • Declare Cursor
  • Open Cursor
  • Retrieve row from the Cursor
  • Process the row
  • Close Cursor
  • Deallocate Cursor

Question #36) What is Collation?

Collation is set of rules that check how the data is sorted by comparing it. Such as Character data is stored using correct character sequence along with case sensitivity, type, and accent.

Question #37) What do we need to check in Database Testing?

Generally, in Database Testing following thing is need to be tested

  • Database Connectivity
  • Constraint Check
  • Required Application Field and its size
  • Data Retrieval and Processing With DML operations
  • Stored Procedures
  • Functional flow

Question #38) What is Database White Box Testing?

Database White Box Testing involves

  • Database Consistency and ACID properties
  • Database triggers and logical views
  • Decision Coverage, Condition Coverage, and Statement Coverage
  • Database Tables, Data Model, and Database Schema
  • Referential integrity rules

Question #39) What is Database Black Box Testing?

Database Black Box Testing involves

  • Data Mapping
  • Data stored and retrieved
  • Use of Black Box techniques such as Equivalence Partitioning and Boundary Value Analysis (BVA)

Question #40) What are Indexes in SQL?

The index can be defined as the way to retrieve the data more quickly. We can define indexes using CREATE statements.

Syntax: CREATE INDEX index_name
ON table_name (column_name)

Further, we can also create Unique Index using following syntax;

Syntax: CREATE UNIQUE INDEX index_name
ON table_name (column_name)

******************

UPDATE: Added more questions for your practice.

Q#41. What does SQL stand for?
Ans. SQL stands for Structured Query Language.

Q#42. How to select all records from the table? 
Ans. To select all the records from the table we need to use the following syntax:

Select * from table_name;

Q#43. Define join and name different types of joins?
Ans. Join keyword is used to fetch data from related two or more tables. It returns rows where there is at least one match in both the tables included in the join. Read more here.
Type of joins are:

  1. Right Join
  2. Outer Join
  3. Full Join
  4. Cross Join
  5. Self Join.

Q#44. What is the syntax to add a record to a table?
Ans. To add a record in a table INSERT syntax is used.

Ex: INSERT into table_name VALUES (value1, value2..);

Q#45. How do you add a column to a table? 
Ans. To add another column in the table following command has been used.

ALTER TABLE table_name ADD (column_name);

Q#46. Define SQL Delete statement.
Ans. Delete is used to delete a row or rows from a table based on the specified condition.
The basic syntax is as follows:

DELETE FROM table_name

WHERE <Condition>

Q#47. Define COMMIT?
Ans. COMMIT saves all changes made by DML statements.

Q#48. What is a primary key? 
Ans. A Primary key is a column whose values uniquely identify every row in a table. Primary key values can never be reused.

Q#49. What are foreign keys?
Ans. When a one table’s primary key field is added to related tables in order to create the common field which relates the two tables, it called a foreign key in other tables.
Foreign Key constraints enforce referential integrity.

Q#50. What is CHECK Constraint? 
Ans. A CHECK constraint is used to limit the values or type of data that can be stored in a column. They are used to enforce domain integrity.

Q#51. Is it possible for a table to have more than one foreign key? 
Ans. Yes, a table can have many foreign keys and only one primary key.

Q#52. What are the possible values for the BOOLEAN data field? 
Ans. For a BOOLEAN data field, two values are possible: -1(true) and 0(false).

Q#53. What is a stored procedure? 
Ans. A stored procedure is a set of SQL queries which can take input and send back output.

Q#54. What is identity in SQL?
Ans. An identity column in the SQL automatically generates numeric values. We can define a start and increment value of identity column.

Q#55. What is Normalization?
Ans. The process of table design to minimize the data redundancy is called normalization. We need to divide a database into two or more table and define relationships between them.

Q#56. What is Trigger? 
Ans. Trigger allows us to execute a batch of SQL code when a table event occurs (Insert, update or delete command executed against a specific table)

Q#57. How to select random rows from a table? 
Ans. Using SAMPLE clause we can select random rows.

Example:
SELECT * FROM table_name SAMPLE(10);

Q#58. Which TCP/IP port does SQL Server run?
Ans. By default SQL Server runs on port 1433.

Q#59. Write a SQL SELECT query that only returns each name only once from a table?
Ans. To get the each name only once, we need to use the DISTINCT keyword.

SELECT DISTINCT name FROM table_name;

Q#60. Explain DML and DDL?
Ans. DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE  are DML statements.

DDL stands for Data Definition Language. CREATE , ALTER, DROP, RENAME are DDL statements.

Q#61. Can we rename a column in the output of SQL query?
Ans. Yes using the following syntax we can do this.

SELECT column_name AS new_name FROM table_name;

Q#62. Give the order of SQL SELECT?
Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. Only the SELECT and FROM clause are mandatory.

Q#63. Suppose a Student column has two columns, Name and Marks. How to get name and marks of top three students.
Ans. SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM Students s2 WHERE s1.marks = s2.marks)

Q#64. What is SQL comments?
Ans. SQL comments can be put by two consecutive hyphens (–).

Q#65. Difference between TRUNCATE, DELETE and DROP commands? 
Ans. DELETE removes some or all rows from a table based on the condition. It can be rolled back.

TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation cannot be rolled back

DROP command removes a table from the database completely.

Q#66. What are the properties of a transaction?
Ans. Generally, these properties are referred as ACID properties. They are:

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability.

Q#67. What do you mean by ROWID? 
Ans. It’s an 18 character long pseudo column attached with each row of a table.

Q#68. Define UNION, MINUS, UNION ALL, INTERSECT ?
Ans. MINUS – returns all distinct rows selected by the first query but not by the second.

UNION – returns all distinct rows selected by either query

UNION ALL – returns all rows selected by either query, including all duplicates.

INTERSECT – returns all distinct rows selected by both queries.

Q#69. What is a transaction?
Ans. A transaction is a sequence of code that runs against a database. It takes the database from one consistent state to another.

Q#70. What is the difference between UNIQUE and PRIMARY KEY constraints? 
Ans. A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys.

The primary key cannot contain Null values whereas Unique key can contain Null values.

Q#71. What is a composite primary key?
Ans. Primary key created on more than one column is called composite primary key.

Q#72. What is an Index?
Ans. An Index is a special structure associated with a table speed up the performance of queries. The index can be created on one or more columns of a table.

Q#73. What is the Subquery? 
Ans. A Subquery is a subset of select statements whose return values are used in filtering conditions of the main query.

Q#74. What do you mean by query optimization? 
Ans. Query optimization is a process in which database system compares different query strategies and select the query with the least cost.

Q#75. What is Collation? 
Ans. Set of rules that define how data is stored, how case sensitivity and Kana character can be treated etc.

Q#76. What is Referential Integrity?
Ans. Set of rules that restrict the values of one or more columns of the tables based on the values of the primary key or unique key of the referenced table.

Q#77. What is Case Function? 
Ans. Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions and returns one of multiple possible result expressions.

Q#78. Define a temp table?
Ans. A temp table is a temporary storage structure to store the data temporarily.

Q#79. How can we avoid duplicating records in a query? 
Ans. By using DISTINCT keyword duplicating records in a query can be avoided.

Q#80. Explain the difference between Rename and Alias?
Ans. Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column.

Q#81. What is a View?
Ans. A view is a virtual table which contains data from one or more tables. Views restrict data access of table by selecting only required values and make complex queries easy.

Q#82. What are the advantages of Views?
Ans. Advantages of Views:

  1. Views restrict access to the data because the view can display selective columns from the table.
  2. Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing.

Q#83. List the various privileges that a user can grant to another user?
Ans.   SELECT, CONNECT, RESOURCES.

Q#84. What is schema? 
Ans. A schema is a collection of database objects of a User.

Q#85. What is Table? 
Ans. A table is the basic unit of data storage in the database management system. Table data is stored in rows and columns.

Q#86. Do View contain Data? 
Ans. No, Views are virtual structure.

Q#87. Can a View based on another View? 
Ans. Yes, A View is based on another View.

Q#88. What is the difference between Having clause and Where clause? 
Ans. Both specify a search condition but Having clause is used only with the SELECT statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaves like WHERE clause only.

Q#89. What is the difference between Local and Global temporary table? 
Ans. If defined in inside a compound statement a local temporary table exists only for the duration of that statement but a global temporary table exists permanently in the DB but its rows disappear when the connection is closed.

Q#90. What is CTE?
Ans. A CTE or common table expression is an expression which contains temporary result set which is defined in a SQL statement.

SET 3 - SQL Queries Question &  Answers

Sample Data To Practice SQL Skill.

Sample Table – Worker

WORKER_ID FIRST_NAME LAST_NAME SALARY JOINING_DATE DEPARTMENT
001 Monika Arora 100000 2014-02-20 09:00:00 HR
002 Niharika Verma 80000 2014-06-11 09:00:00 Admin
003 Vishal Singhal 300000 2014-02-20 09:00:00 HR
004 Amitabh Singh 500000 2014-02-20 09:00:00 Admin
005 Vivek Bhati 500000 2014-06-11 09:00:00 Admin
006 Vipul Diwan 200000 2014-06-11 09:00:00 Account
007 Satish Kumar 75000 2014-01-20 09:00:00 Account
008 Geetika Chauhan 90000 2014-04-11 09:00:00 Admin

Sample Table – Bonus

WORKER_REF_ID BONUS_DATE BONUS_AMOUNT
1 2016-02-20 00:00:00 5000
2 2016-06-11 00:00:00 3000
3 2016-02-20 00:00:00 4000
1 2016-02-20 00:00:00 4500
2 2016-06-11 00:00:00 3500

Sample Table – Title

WORKER_REF_ID WORKER_TITLE AFFECTED_FROM
1 Manager 2016-02-20 00:00:00
2 Executive 2016-06-11 00:00:00
8 Executive 2016-06-11 00:00:00
5 Manager 2016-06-11 00:00:00
4 Asst. Manager 2016-06-11 00:00:00
7 Executive 2016-06-11 00:00:00
6 Lead 2016-06-11 00:00:00
3 Lead 2016-06-11 00:00:00

To prepare the sample data, you can run the following queries in your database query executor or on the SQL command line. We’ve tested them with MySQL Server 5.7 and MySQL Workbench 6.3.8 query browser. You can also download these Softwares and install them to carry on the SQL exercise.

SQL Script To Seed Sample Data.

CREATE DATABASE ORG;
SHOW DATABASES;
USE ORG;

CREATE TABLE Worker (
	WORKER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	FIRST_NAME CHAR(25),
	LAST_NAME CHAR(25),
	SALARY INT(15),
	JOINING_DATE DATETIME,
	DEPARTMENT CHAR(25)
);

INSERT INTO Worker 
	(WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT) VALUES
		(001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR'),
		(002, 'Niharika', 'Verma', 80000, '14-06-11 09.00.00', 'Admin'),
		(003, 'Vishal', 'Singhal', 300000, '14-02-20 09.00.00', 'HR'),
		(004, 'Amitabh', 'Singh', 500000, '14-02-20 09.00.00', 'Admin'),
		(005, 'Vivek', 'Bhati', 500000, '14-06-11 09.00.00', 'Admin'),
		(006, 'Vipul', 'Diwan', 200000, '14-06-11 09.00.00', 'Account'),
		(007, 'Satish', 'Kumar', 75000, '14-01-20 09.00.00', 'Account'),
		(008, 'Geetika', 'Chauhan', 90000, '14-04-11 09.00.00', 'Admin');

CREATE TABLE Bonus (
	WORKER_REF_ID INT,
	BONUS_AMOUNT INT(10),
	BONUS_DATE DATETIME,
	FOREIGN KEY (WORKER_REF_ID)
		REFERENCES Worker(WORKER_ID)
        ON DELETE CASCADE
);

INSERT INTO Bonus 
	(WORKER_REF_ID, BONUS_AMOUNT, BONUS_DATE) VALUES
		(001, 5000, '16-02-20'),
		(002, 3000, '16-06-11'),
		(003, 4000, '16-02-20'),
		(001, 4500, '16-02-20'),
		(002, 3500, '16-06-11');
CREATE TABLE Title (
	WORKER_REF_ID INT,
	WORKER_TITLE CHAR(25),
	AFFECTED_FROM DATETIME,
	FOREIGN KEY (WORKER_REF_ID)
		REFERENCES Worker(WORKER_ID)
        ON DELETE CASCADE
);

INSERT INTO Title 
	(WORKER_REF_ID, WORKER_TITLE, AFFECTED_FROM) VALUES
 (001, 'Manager', '2016-02-20 00:00:00'),
 (002, 'Executive', '2016-06-11 00:00:00'),
 (008, 'Executive', '2016-06-11 00:00:00'),
 (005, 'Manager', '2016-06-11 00:00:00'),
 (004, 'Asst. Manager', '2016-06-11 00:00:00'),
 (007, 'Executive', '2016-06-11 00:00:00'),
 (006, 'Lead', '2016-06-11 00:00:00'),
 (003, 'Lead', '2016-06-11 00:00:00');

Once above SQL would run, you’ll see a result similar to the one attached below.

SQL Query Questions - Creating Sample Data

Creating Sample Data to Practice SQL Skill.

50 SQL Query Questions And Answers For Practice.

Q-1. Write An SQL Query To Fetch “FIRST_NAME” From Worker Table Using The Alias Name As <WORKER_NAME>.

Ans.

The required query is:

Select FIRST_NAME AS WORKER_NAME from Worker;

 

Q-2. Write An SQL Query To Fetch “FIRST_NAME” From Worker Table In Upper Case.

Ans.

The required query is:

Select upper(FIRST_NAME) from Worker;

 

Q-3. Write An SQL Query To Fetch Unique Values Of DEPARTMENT From Worker Table.

Ans.

The required query is:

Select distinct DEPARTMENT from Worker;

 

Q-4. Write An SQL Query To Print First Three Characters Of  FIRST_NAME From Worker Table.

Ans.

The required query is:

Select substring(FIRST_NAME,1,3) from Worker;

 

Q-5. Write An SQL Query To Find The Position Of The Alphabet (‘A’) In The First Name Column ‘Amitabh’ From Worker Table.

Ans.

The required query is:

Select INSTR(FIRST_NAME, BINARY'a') from Worker where FIRST_NAME = 'Amitabh';

Notes.

  • The INSTR method is in case-sensitive by default.
  • Using Binary operator will make INSTR work as the case-sensitive function.

 

Q-6. Write An SQL Query To Print The FIRST_NAME From Worker Table After Removing White Spaces From The Right Side.

Ans.

The required query is:

Select RTRIM(FIRST_NAME) from Worker;

 

Q-7. Write An SQL Query To Print The DEPARTMENT From Worker Table After Removing White Spaces From The Left Side.

Ans.

The required query is:

Select LTRIM(DEPARTMENT) from Worker;

 

Q-8. Write An SQL Query That Fetches The Unique Values Of DEPARTMENT From Worker Table And Prints Its Length.

Ans.

The required query is:

Select distinct length(DEPARTMENT) from Worker;

 

Q-9. Write An SQL Query To Print The FIRST_NAME From Worker Table After Replacing ‘A’ With ‘A’.

Ans.

The required query is:

Select REPLACE(FIRST_NAME,'a','A') from Worker;

 

Q-10. Write An SQL Query To Print The FIRST_NAME And LAST_NAME From Worker Table Into A Single Column COMPLETE_NAME. A Space Char Should Separate Them.

Ans.

The required query is:

Select CONCAT(FIRST_NAME, ' ', LAST_NAME) AS 'COMPLETE_NAME' from Worker;

 

Q-11. Write An SQL Query To Print All Worker Details From The Worker Table Order By FIRST_NAME Ascending.

Ans.

The required query is:

Select * from Worker order by FIRST_NAME asc;

 

Q-12. Write An SQL Query To Print All Worker Details From The Worker Table Order By FIRST_NAME Ascending And DEPARTMENT Descending.

Ans.

The required query is:

Select * from Worker order by FIRST_NAME asc,DEPARTMENT desc;

 

Q-13. Write An SQL Query To Print Details For Workers With The First Name As “Vipul” And “Satish” From Worker Table.

Ans.

The required query is:

Select * from Worker where FIRST_NAME in ('Vipul','Satish');

 

Q-14. Write An SQL Query To Print Details Of Workers Excluding First Names, “Vipul” And “Satish” From Worker Table.

Ans.

The required query is:

Select * from Worker where FIRST_NAME not in ('Vipul','Satish');

 

Q-15. Write An SQL Query To Print Details Of Workers With DEPARTMENT Name As “Admin”.

Ans.

The required query is:

Select * from Worker where DEPARTMENT like 'Admin%';

 

Q-16. Write An SQL Query To Print Details Of The Workers Whose FIRST_NAME Contains ‘A’.

Ans.

The required query is:

Select * from Worker where FIRST_NAME like '%a%';

 

Q-17. Write An SQL Query To Print Details Of The Workers Whose FIRST_NAME Ends With ‘A’.

Ans.

The required query is:

Select * from Worker where FIRST_NAME like '%a';

 

Q-18. Write An SQL Query To Print Details Of The Workers Whose FIRST_NAME Ends With ‘H’ And Contains Six Alphabets.

Ans.

The required query is:

Select * from Worker where FIRST_NAME like '_____h';

 

Q-19. Write An SQL Query To Print Details Of The Workers Whose SALARY Lies Between 100000 And 500000.

Ans.

The required query is:

Select * from Worker where SALARY between 100000 and 500000;

 

Q-20. Write An SQL Query To Print Details Of The Workers Who Have Joined In Feb’2014.

Ans.

The required query is:

Select * from Worker where year(JOINING_DATE) = 2014 and month(JOINING_DATE) = 2;

 

Q-21. Write An SQL Query To Fetch The Count Of Employees Working In The Department ‘Admin’.

Ans.

The required query is:

SELECT COUNT(*) FROM worker WHERE DEPARTMENT = 'Admin';

 

Q-22. Write An SQL Query To Fetch Worker Names With Salaries >= 50000 And <= 100000.

Ans.

The required query is:

SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) As Worker_Name, Salary
FROM worker 
WHERE WORKER_ID IN 
(SELECT WORKER_ID FROM worker 
WHERE Salary BETWEEN 50000 AND 100000);

 

Q-23. Write An SQL Query To Fetch The No. Of Workers For Each Department In The Descending Order.

Ans.

The required query is:

SELECT DEPARTMENT, count(WORKER_ID) No_Of_Workers 
FROM worker 
GROUP BY DEPARTMENT 
ORDER BY No_Of_Workers DESC;

 

Q-24. Write An SQL Query To Print Details Of The Workers Who Are Also Managers.

Ans.

The required query is:

SELECT DISTINCT W.FIRST_NAME, T.WORKER_TITLE
FROM Worker W
INNER JOIN Title T
ON W.WORKER_ID = T.WORKER_REF_ID
AND T.WORKER_TITLE in ('Manager');

 

Q-25. Write An SQL Query To Fetch Duplicate Records Having Matching Data In Some Fields Of A Table.

Ans.

The required query is:

SELECT WORKER_TITLE, AFFECTED_FROM, COUNT(*)
FROM Title
GROUP BY WORKER_TITLE, AFFECTED_FROM
HAVING COUNT(*) > 1;

 

Q-26. Write An SQL Query To Show Only Odd Rows From A Table.

Ans.

The required query is:

SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;

 

Q-27. Write An SQL Query To Show Only Even Rows From A Table.

Ans.

The required query is:

SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) = 0;

 

Q-28. Write An SQL Query To Clone A New Table From Another Table.

Ans.

The general query to clone a table with data is:

SELECT * INTO WorkerClone FROM Worker;

The general way to clone a table without information is:

SELECT * INTO WorkerClone FROM Worker WHERE 1 = 0;

An alternate way to clone a table (for MySQL) without is:

CREATE TABLE WorkerClone LIKE Worker;