CÂU HỎI PHỎNG VẤN AUTOMATION TESTER (Tiếng Anh)

Anh Tester chia sẻ đến với bạn một số câu hỏi phỏng vấn Automation Tester bằng Tiếng Anh mà các nhà tuyển dụng thường hỏi, các bạn có thể tham khảo để chuẩn bị tốt hơn cho buổi phỏng vấn của mình.

Để có thể vượt qua các vòng tuyển dụng Automation Tester, bạn cần chuẩn bị trước ở nhà một số tình huống có thể xảy ra. Sau đây là một số các câu hỏi phỏng vấn thường gặp.

Các câu hỏi về thông tin và kinh nghiệm cá nhân

Các câu hỏi đầu tiên bạn nhận được khi tham gia buổi tuyển dụng Automation Tester là về thông tin và kinh nghiệm của bạn.

Các nhà tuyển dụng sẽ hỏi các câu hỏi như: “Bạn hãy giới thiệu về mình?”, “Tại sao bạn lại chọn nghề Tester?”, “Kinh nghiệm làm nghề Automation Tester của bạn trong quá khứ?”.

Bạn hãy trả lời các câu hỏi này một cách chân thật nhất về những kỹ năng mình có.

 

Các câu hỏi về kiến thức Automation Testing


  1. Can you brief me about yourself? 

Hi, my name is Anh Tester. 

I started my career as a Testing Executive 4 years back with Infosys currently I  am working as Test Engineer. 

My responsibility is to understand Business Requirement Specification and High Level scenarios and to convert them into test cases & Automation scripts if required. Execution of test cases and reporting of defect to the developer if there any and  get them fixed. I have experience on Functional, Automation, Regression,  Smoke, Sanity, Web accessibility, Web Analytics, Mobile Testing. 

In my previous project I have worked on Automation testing where we have used  Selenium with java and TestNG Cucumber framework for BDD approach. We have  used Page object model where we have separated our test cases with page objects,  and we performed testing on the same. For build management tool we are using Maven  for version controlling we are using Git and for automating our jobs for nightly run or  any schedule we are using Jenkins. 

For defect management & test case management we have used JIRA, TEST RAIL & HP  ALM. I have worked on tools like BrowseStack, DeviceAnywhere, Toadsql, I am working on Agile environment we have daily standup call and we have 2-week  sprint cycle. I am part of 8-member team out of which we are 3-Tester, 2- dev, 1- manager, 1-scrum master. 

  1. Tell me your Day to Day activities as QA? 

First thing I do after login in my system. I check the active sprint in Jira for our project  code. There I can see my assigned open tasks. After that I will check my mail if there is  any important mail I need to take action on. Then we have our daily scrum meeting  where we used to tell our previous day actions what we did, what we are planning for  today and if we have any blocker to discuss. Product owner and scrum master help us  to resolve that blocker. After that I need to take the pending task and do needed action  whether creating test case, Execution, Defect retesting if any. 

  1. Do you have created framework from scratch, or you have maintained that? I have not created Framework from scratch by myself but yes, I was part of  framework creation and created some part of it. 
  2. How much you rate yourself in Java out of 10? 

Out of 10 I will rate myself 8 in java as QA Automation engineer. 

  1. Can you tell me Oops concepts and relate it with your Framework? We have Polymorphism, Inheritance, Encapsulation and Abstraction in Oops. So, we will  start with 

1) DATA ABSTRACTION 

Data Abstraction means to handle complexity by hiding unnecessary details from  the user. In java, abstraction is achieved by interfaces and abstract classes. We  can achieve 100% abstraction using interfaces. 

In Selenium, WebDriver itself acts as an interface. Consider the below statement:

 

WebDriver driver = new ChromeDriver(); 

We initialize the Chrome Browser using Selenium Webdriver. It means we are creating  a reference variable (driver) of the interface (WebDriver) and creating an Object. Here  WebDriver is an Interface and ChromeDriver is a class. 

We can apply Data Abstraction in a Selenium framework by using the Page Object  Model design pattern. We define all our locators and their methods in the page class.  We can use these locators in our tests but we cannot see the implementation of their  underlying methods. So we only show the locators in the tests but hide the  implementation. This is a simple example of how we can use Data Abstraction in our  Automation Framework. 

2)ENCAPSULATION 

Encapsulation is defined as the wrapping up of data under a single unit. It is the  mechanism that binds together code and the data it manipulates. Encapsulation can be  achieved by: Declaring all the variables in the class as private and writing public  methods in the class to set and get the values of variables. 

All the classes in an Automation Framework are an example of Encapsulation. In  Page Object Model classes, we declare the data members using @FindBy and  initialization of data members will be done using Constructor to utilize those in  methods. 

3)INHERITANCE 

Inheritance is the mechanism in java by which one class is allowed to inherit the  features (fields and methods) of another class. 

We can apply Inheritance in our Automation Framework by creating a Base Class to  initialize the WebDriver interface, browsers, waits, reports, logging, etc. and then we can  extend this Base Class and its methods in other classes like Tests or Utilities. This is a  simple example of how we can apply Inheritance in our framework. 

4) POLYMORPHISM 

Polymorphism allows us to perform a single action in different ways. In Java  polymorphism can be achieved by two ways: 

Method Overloading: When there are multiple methods with same name but different  parameters then these methods are said to be overloaded. Methods can be overloaded  by change in number of arguments or/and change in type of arguments. 

In Selenium Automation, Implicit wait is an example of Method Overloading. In  Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS  etc. 

Method Overriding: It occurs when a derived class has a definition for one of the  member functions of the base class. That base function is said to be overridden. In Selenium Automation, Method Overriding can be achieved by overriding any  WebDriver method. For example, we can override the findElement method In assertion we have used overload because in assertion we used to like  asset.true(actual, expected) and second time we can use same assert.true(actual,  expected, message). 

  1. How can you use interface and how it is different from Abstract class?

 

Abstract class may have Abstract and concrete methods, and there is not any  compulsion in adding abstract method in abstract class. But in Interface, we do have  only abstract methods and we don’t need to write abstract keyword in Interface this is  by default public and abstract. 

  1. What do you mean by Static keyword in Java? 

Static means it is at class level not at instance level, we have static method, static  variable & static inner class. When we have any variable as static so it will remain  same for all the instance of our classes, and static/Private/Final methods can’t be  over-ridden like if we have initialized any method as Static so we cannot override it in  any child class. 

  1. How to call static method and variable in java? 

Direct calling, Calling by class name. 

  1. Can I access Static method by using object reference? 

Yes we can, but we got one warning that you need to access it via Direct or By class  name. 

  1. How to call non-static method and variable in java? 

For calling non static method we need to create object first. 

  1. Can we overload & override main  

method? Overload-Yes, Override 

No 

  1. What do you mean by wrapper class and how will you do data conversion? Wrapper class in java are used for data conversion. In data conversion if user  wants to convert Int to string, String to int, Boolean, double then we use Wrapper  class. 

integer.parseInt(); - To convert string to  

Integer Double.parseDouble(); - To convert  

string to Double Boolean.parse Boolean(); - 

To convert string to Boolean String.valueof(); - 

To convert Integer to String. 

  1. Can you convert string a =”110a” in integer? 

No we got NumberFormatException while converting the above string. 

  1. What do you mean by Call by Value & Call by Reference in Java? Call by value means suppose we have created one sum method with input parameter  int a, int b. So while calling the creating the object and running we provide values that is  know as call by value. 
  2. What do you mean by Exceptions in Java? 

Exception is like any interruption in our normal flow. Like if we are running anything and  we got issues in our script this is we called exception, we have 2 types of exception  Run Time & Compile Time. (checked & Unchecked exceptions)

 

  1. Can you tell me about difference between Throw and Throws keyword? Throw is a keyword used inside a body of function. And Throws used while initializing  any method. By using Throw we can throw only one exception while for Throws we can  declare multiple exceptions which might occur in that particular function. Throws  keyword followed by instance name and Throw keyword is followed by class name of  that exception. 
  2. How much you rate yourself in  

selenium out of 5? Out of 5 I will rate  

myself 3.5 in selenium. 

  1. Which locator you are using in your framework and why? 

Mostly we used ID and Xpath because Id is the fastest and unique one and after that  we prefer Xpath. Anyways we have other locators as well like css , class name, tag  name, Link text, Partial Link text. 

  1. What is the difference between findelement & findelements? 

findelement will give the first appearance of that element which matches our locator,  whereas findelements will give us list of all the elements which is present over the  webpage and matching our locator. And if we don’t find the element findelement will  give us nosuchelementexception whereas findelements will return NULL/Empty list. 

  1. Why declaring the driver object as static in base class is not a good practice in  selenium? What are the challenges we might face if we do the same? If you perform sequential test case execution, then it will work perfectly. But when you  do the same thing for parallel execution it will stop the execution because your first test  case will use your driver object but at the same another testcase running parallelly they  will also grab the driver object so it may through null pointer exception or may get some  weird result and your script will fail. But if you want to declare driver object as static you  can do. By defining local variable of driver object in each class. 
  2. What are the conditions that throws ClassCastException? 

Integer to string, string is not a subclass of Integer, so a Class Cast  Exception will be thrown. Object I = Integer.valueOf(42); 

String s = (String)i; 

  1. Can you tell me how you will handle multiple windows in selenium? We have windowhandle & windowhandles function for handling Multiple windows.  Windowhandle will give the string value of only the active window that is open whereas  windowhandles will give set of all the windows that are open in browser. 
  2. How you will move from one window to another? 

First we will check what all windows are open by using driver.getwindowhandles, to  get set of opened windows , then I use iterator to iterate over each of the pages and  inside for loop will check like Current URL matches with the excepted page, if match  then switch to that window by using driver.switchTo(Destination window) -> to return  back to main parent window use driver.defaultContent().

 

  1. Tell me the difference between Implicit & Explicit wait? 

Implicit wait applies for all the elements and all the tests like if we give 10 sec of implicit wait it will wait for 10 sec for each element before giving nosuchelement  exceptions. 

While Explicit wait can be applied for any particular step for which you want extra wait  time so we can use explicit wait. We can use mix of both waits to depend on the  situation of the step. 

  1. Can you tell me some exceptions in selenium? 

NoSuchElementException, NoSuchWindowException  

NoSuchframeException, StaleElementReferenceException,  

TimeoutException. 

  1. Can you tell me about StaleElementReferenceException? 

Stale means old or decayed, here it sounds like element which was present on that  page is no longer there or decayed. To handle this, we can refresh the webpage  before pointing to that element. We can write script for waiting via explicit wait by  writing expected condition.refresh. Or we can go with page object model in that we  can over come this stale element exception. 

  1. What do you mean by User Defined Exception? 

User Defined Exception or custom exception is creating your own exception class and  throws 

that exception using 'throw' keyword. This can be done by extending the class  Exception. ... The keyword “throw” is used to create a new Exception and throw it to the  catch block. 

  1. Can you tell me what is assert in TestNG? 

Assert is like verification where we check like expected thing and actual thing are same  or not. 

  1. Which assert you have used in TestNg? 

We have used Hard assert and Soft assert, while applying Hard assert if we found any  glitch in expected and actual then it will through exception and move to next @test while  Soft assert it won’t give exception and move to next step of that test. And to get all the  exceptions in console we need to write at the end assert.all. 

  1. Can you tell me about the order of TestNG annotations?
  • @BeforeSuite/@AfterSuite
  • @BeforeTest/@AfterTest
  • @BeforeGroups/@AfterGroups
  • @BeforeClass/@AfterClass
  • @BeforeMethod/@AfterMethod
  • @Test

 

  1. Do you heard about Priority in TestNg can we set -ve priority? 

Yes, like priority is 0, -1, TestNg will run -1 then 0 then 1. And if we have any @test  which is not having any priority set, then in that case it will search via alphabetic order  whichever comes first and execute test respectively. 

  1. Do you work in cucumber, can you tell me what all files  

required in cucumber? In cucumber we have Feature file, Step  

Definition file and Test Runner file. 

In feature file we used to write scenario in gherkin language which is most like in plain  English language. Here we use some of the keywords like feature, scenario, scenario  outline, given, when, then, and, example, background keywords for writing our test scenarios steps. 

In Step Definition file we write mapping code for all the scenario of feature file. In test Runner file we provide the address of the feature file, step definition file, and  all-important Tags, Plugin, Listeners in that. 

  1. What is the difference between scenario & scenario outline? 

When we have single scenario and we need to run it one time at that place we use  Scenario. 

If you want some parametrization or Data Driven testing at that time, we can use  scenario outline where we have to use Example keyword like if we are running this  scenario for 3 different data set like username & pass. so, it will run 3 times. 

  1. Can you tell me more about Background Keyword? 

Background is used when we have some common Given part. Suppose we have  pre-condition that we have to check this before each scenario. so in order to avoid  rewriting same step we can write it in Background. 

  1. What is the use of Dry Run in cucumber? 

Dry run is not running our whole application it will check whether all features are  mapped with Step definition. 

  1. What is hooks in cucumber? 

In cucumber we use hooks for common functionalities, hooks are like we want to run  before & after each of the scenario. In hooks we have 2 different @before, @ after  which run before and after of each scenario. Also @beforestep, @afterstep which run  before and after each step. 

  1. Can you tell me how you will re-run failed scenario in cucumber? For that we can use re-run attribute in our test runner file. After that we can write one file  location. Where all the test cases which failed while execution get stored. So next time  while running execution we can give this file location and run the failed TC. 
  2. You have worked in Cucumber & TestNG according to you which one is best? I will consider Cucumber as it is most likely understood by Laymen people which is  English plain language. Because in order to understand the functionality flow no need to  go look and script/code. Via Scenario steps lines only we can get clear understanding  about the functionality.

 

It helps to come all the QA members Dev, Client, Product Owner on same page. 

  1. Can you explain me TestNG? 

TestNG is advanced version of Junit only. It is mainly used by Dev/QA for maintain the  code easily and for unit testing. It provides lots of benefits to us like we can create a  suite and we can write all the required Tc in one go only using that suite. We can group  our Tc we can set priority we can run our tc in parallel mode, We can generate good  reports via TestNG. We can write functionality depends on methods, depends on group.  We can run single tc multiple time with single set of data of multiple set of Data. 

  1. How to run single method multiple time in TestNG? 

We have invocation count attribute in @test annotiation. We can write invocation count  as 3 if we want to run it 3 times. Apart from that we can write threadpull.size if we want  to run that case in multiple thread. 

  1. Have you used GIT in your project can you explain about it? 

Yes I have used GIT, It is a version control tool. Where we can maintain our central  repo. we used to manage our code via GIT only. We use Git to maintain our project in  our local system. So, if someone like to work on that project I need to send complete  update copy to him and after that he can work on that. There are chances that single  project is handled by multiple teams across the globe. So, it will be difficult if we won’t  use GIT. 

  1. Can you give me some GIT commands which you used on daily basis? Git status- which shows status of all the files,if we have some files which is not yet  added to our repo so it will give us untracked file. 

After that we can use GIT add command after adding it will added to particular index  and we can commit this file using Git Commit-(Message) we can commit this untracked  file. Also we have Git Merge, Git Post, Git Pull, Git It in etc. 

  1. How to solve Merge conflict in GIT? 

As we are only 2 tester working on this project, if we have any merge conflict I used to  pull all the latest file/scripts to my local system. Then I will analyze the difference  between that particular file and merge file. After that I will check with my team member  whether all his imp things are covered then I will add my steps and push the script to the  central repo. 

  1. You have worked in Jenkins can you tell me how you have created jobs in  Jenkins? 

We have separate Dev-Ops Team to create Jenkins jobs at broad level but we also  have access to jenkins, so we have created jobs for our internal purpose. For creating any job we have click on create new job->inside that give name of your job- >select freestyle project->then add. Beside that we can provide description of our project  and in source code management we can choose Git-> provide repo url ->after that  provide some schedule if you want to run the job on any specific schedule time.-> select  window batch command-file location-save-click on build now for running. After triggering  we can check log in console.

 

  1. What is the difference between Smoke & Sanity Testing? 

Smoke and Sanity we can are like same thing because both are checking important  functionality. Smoke testing is done on first stable build from developer to check like  whether it is stable enough to move further or not. While Sanity testing is subset of  regression test which we perform on stable build and here also we used to check all  the imp functionality. 

  1. What is Agile ceremony? 

We have 4 Agile ceremony -Sprint planning, Sprint review, Sprint Retrospective, Daily  scrum meeting. 

  1. Why the main method is static? 

Java main() method is always static, so that compiler can call it without the creation of  an object or before the creation of an object of the class. ... Static method of a class can  be called by using the class name only without creating an object of a class. 

  1. What is Run time polymorphism 

Run-Time Polymorphism: Whenever an object is bound with the functionality at run  time, this is known as runtime polymorphism. The runtime polymorphism can be  achieved by method overriding. Java virtual machine determines the proper method to  call at the runtime, not at the compile time

  1. Difference between list and set. 

The main difference between List and Set is that Set is unordered and contains  different elements, whereas the list is ordered and can contain the same elements  in it. 

  1. Method overloading and overriding. 

Method overriding is used to provide the specific implementation of the method that  is already provided by its super class. Method overloading is performed within class.  Method overriding occurs in two classes that have IS-A (inheritance) relationship. In  case of method overloading, parameter must be different. 

  1. Use of constructor. 

The purpose of constructor is to initialize the object of a class while the purpose of  a method is to perform a task by executing java code. Constructors cannot be  abstract, final, static and synchronised while methods can be. Constructors do not  have return types while methods do. 

  1. Difference between static and non-static methods 

Static method uses complie time binding or early binding. Non-static method uses  run time binding or dynamic binding. A static method cannot be overridden being 

 

compile time binding. A non-static method can be overridden being dynamic  binding. 

  1. Explain Git workflow. 

Step 1: Set up a Github Organization. ... 

Step 2: Fork Organization Repository to Your Personal GitHub. ... 

Step 3: Clone the Repository to Your Local Machine. ... 

Step 4: Create a Branch for your Working Files. ... 

Step 5: Set Remote Repository to the GitHub Organization. ... 

Step 6: Get Coding! 

Step 7: Pull the Most Recent Files From the Organization Repo 

Step 8: Merge the Master Branch Into the Feature Branch 

Step 9: Push Your Code to your GitHub Repo 

Step 10: Make a Pull Request to the Organization Repo 

  1. How to set up Jenkins? 

Step 1 − Go to the Jenkins dashboard and Click on New Item 

Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld.  Choose the ‘Freestyle project option’ 

Step 3 − The following screen will come up in which you can specify the details of the job. Step 4 − We need to specify the location of files which need to be built. In this example, we  will assume that a local git repository(E:\Program) has been setup which contains a  ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of  the local git repository. 

Note − If you repository if hosted on Github, you can also enter the url of that repository  here. In addition to this, you would need to click on the Add button for the credentials to add  a user name and password to the github repository so that the code can be picked up from  the remote repository. 

Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch  command 

Step 6 − In the command window, enter the following commands and then click on the Save  button. 

Javac HelloWorld.java 

Java HelloWorld 

Step 7 − Once saved, you can click on the Build Now option to see if you have successfully  defined the job. 

Step 8 − Once the build is scheduled, it will run. The following Build history section shows  that a build is in progress. 

Step 9 − Once the build is completed, a status of the build will show if the build was  successful or not. In our case, the following build has been executed successfully. Click on  the #1 in the Build history to bring up the details of the build. 

Step 10 − Click on the Console Output link to see the details of the build 

  1. Can we declare many interfaces object class inside the interface class.

 

Yes, you can define a class inside an interface. In general, if the methods  of the interface use this class and if we are not using it anywhere else we  will declare a class within an interface

  1. Types of the assertion. 

Selenium Assertions can be of three types: “assert”, “verify”, and ” waitFor”. When  an “assert” fails, the test is aborted. When a “verify” fails, the test will continue  execution, logging the failure. A “waitFor” command waits for some condition to  become true. 

  1. Abstraction in java and exp? 

In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,)  in a Page Class. We utilize these locators in tests but we can’t see these locators in the  tests. Literally we hide the locators from the tests. 

  1. What is a super keyword in java? 

The super keyword refers to superclass (parent) objects. It is used to call  superclass methods, and to access the superclass constructor. The most common  use of the super keyword is to eliminate the confusion between superclasses and  subclasses that have methods with the same name. 

  1. Difference between break and continue statement. 

Break statement resumes the control of the program to the end of loop and made  executional flow outside that loop. Continue statement resumes the control of the  program to the next iteration of that loop enclosing 'continue' and made executional  flow inside the loop again 

  1. Diff between Abstract class & interface? 

Abstract class can inherit another class using extends keyword and implement an interface. Interface can inherit only an inteface. Abstract class can be  inherited using extends keyword. Interface can only be implemented using  implements keyword. 

  1. What is a static keyword in Java? 

In the Java programming language, the keyword static indicates that the particular  member belongs to a type itself, rather than to an instance of that type. This means that  only one instance of 

that static member is created which is shared across all instances of the class. 62. Have you used the action class and where it is used? 

Using the Actions class in Selenium, we can implement the sendKeys() method to  type specific values in the application. That is how you use the actions class in  Selenium with sendKeys() method. ... The perform() method is used to perform the  series of actions that are defined.

 

  1. What is the difference between checked and unchecked exceptions? 

There are two types of exceptions: checked exception and unchecked exception.  ... The main difference between checked and unchecked exception is that the  checked exceptions are checked at compile-time while unchecked exceptions are  checked at runtime 

checked exceptions SQLException,IOException,ClassNotFoundException,InvocationTargetException 

unchecked exceptions – 

NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException,IllegalArgume ntException 

NumberFormatException 

  1. Apart from sendkeys, are there any different ways, to type content onto the  editable field? 

WebDriver driver = new FirefoxDriver(); JavascriptExecutor executor =  (JavascriptExecutor)driver;  

executor.executeScript("document.getElementById("textbox_id").value= 

'new value';); 

  1. What is static and non-static? 

In non-static method, the method can access static data members and static methods  as well as non-static members and method of another class or same class. Binding  process. Static method uses compile time or early binding. Non-static method uses  runtime or dynamic binding. Overriding. 

  1. DIfference between this and super? 

this keyword mainly represents the current instance of a class. On other hand super keyword represents the current instance of a parent class. this keyword used to call  default constructor of the same class. 

  1. What is the difference between length and length() in Java? 

The length is an instance variable of an array in Java whereas length() is a method of  String class 

  1. What is an abstract class? 

Abstract Classes and Methods Abstract class: is a restricted class that cannot be  used to create objects

 

(to access it, it must be inherited from another class). Abstract method: can only be  used in an abstract class, and it does not have a body. The body is provided by the  subclass (inherited from). 

  1. Difference between Actions and Action? 

Actions is a class that is based on a builder design pattern. This is a user-facing API  for emulating complex user gestures. Whereas Action is an Interface which represents  a single user-interaction action. 

  1. How do you handle keystrokes in Selenium? 

Using Actions Class: Actions action = new Actions(driver); action. keyDown(Keys. ... Using SendKeys Chord: driver. findElement(By. ... 

Using Robot Class: // Create Robot class Robot rb = new Robot(); // Press control  keyboard key rb. 

  1. What is dry run in Cucumber? 

Dry-run is used to compile feature files and step definitions in cucumber. It is  specially used in the stage when you will have to see if there are any compilation  errors, to check that you can use dry-run. Dry-run options can either set as true or  false. 

  1. Annotations in Cucumber 

Total 11 Annotations -Feature, Scenario, Background, given, when , then, and, but,  example, scenario outline, scenario template. 

  1. What are hashmap and HashSet? Explain? 

HashMap and HashSet both are one of the most important classes of Java Collection  framework. 

... HashMap Stores elements in form of key-value pair i.e each element has its  corresponding key which is required for its retrieval during iteration. HashSet stores  only objects no such key value pairs maintained. 

  1. Where do you use a hashmap? 

Maps are used for when you want to associate a key with a value and Lists are an  ordered collection. Map is an interface in the Java Collection Framework and a  HashMap is one implementation of the Map interface. HashMap are efficient for  locating a value based on a key and inserting and deleting values based on a key. 

HashMap<String, Integer> map = new HashMap<>(); 

// Add elements to the map 

map.put("vishal", 10); 

map.put("sachin", 30);

 

map.put("vaibhav", 20); 

// Print size and content 

System.out.println("Size of map is:- " + map.size()); 

System.out.println(map); 

// Check if a key is present and if present, print value 

if (map.containsKey("vishal")) { 

Integer a = map.get("vishal"); 

System.out.println("value for key"+ " \"vishal\" is:- " + a); 

  1. How do you handle if XPath is changing dynamically? 

Option 1: Look for any other attribute which Is not changing every time In that div  node like name, class etc. So If this div node has class attribute then we can write  xpath as bellow. 

//div[@class='post-body entry-content']/div[1]/form[1]/input[1] 

Option 2: We can use absolute xpath (full xpath) where you do not need to give any  attribute names In 

xpath. 

/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div/div/div[1]/div /div/di 

v/div[1]/div[2]/div[1]/form[1]/input[1] 

Option 3: We can use starts-with function. In this xpath's ID attribute, "post-body-"  part remains same every time. //div[starts-with(@id,'post-body- ')]/div[1]/form[1]/input[1] 

Option 4: We can use contains function. Same way you can use  

contains function as bellow.div[contains(@id,'post-body- 

')]/div[1]/form[1]/input[1] 

  1. Does Jenkins require a local system for CI? 

It is a server-based application and requires a web server like Apache Tomcat 77. What is a singleton class? 

The Singleton's purpose is to control object creation, limiting the number of objects to  only one. Since there is only one Singleton instance, any instance fields of a Singleton  will occur only once per class, just like static fields. Singletons often control access to  resources, such as database connections or sockets.

 

For example, if you have a license for only one connection for your database or your  JDBC driver has trouble with multithreading, the Singleton makes sure that only one  connection is made or that only one thread can access the connection at a time. 

  1. When finally block get executed? 

The finally block always executes when the try block exits. This  ensures that the finally block is executed even if an unexpected  exception occurs. 

  1. How many times you can write catch block? 

maximum one catch block will be executed. No, we can write multiple catch  block but only one is executed at a time. 

  1. What Maven Architecture and explain pom.xml? 

POM is an acronym for Project Object Model. The pom. xml file contains  information of project and configuration information for the maven to build the  project such as dependencies, build directory, source directory, test source  directory, plugin, goals etc. Maven reads the pom.

 

REAL TIME SELENIUM + JAVA INTERVIEW QUESTIONS 

  1. How many types of WebDriver API ’s are available in selenium? 

Chrome, Geko, Chromium, Edge, html, android, 

  1. How can you make sure that page is loaded via wed  

driver or selenium? Via first apply wait , is element present,  

then get text. 

  1. How can we launch a batch file in selenium webdriver project? 

Take path of batch file->process.batchjob= runtime.get(runtime.executable”Path”)); 4. How do you run selenium webdriver test from the  

command line? For that go to cmd-> java-class path(of the  

selenium project) ->hit enter 

  1. What are the different exception you faced in selenium webdriver? Webdriver exc, noalertpresent exc, nosuchwindow exc, nosuchelement exc, timeout exc. 6. How do you scroll down a page using  

javascript in selenium? Windows.scrollby  

function 

  1. How do you scroll down to a  

particular element?  

Windows.scroll.intoview function 

  1. Which all files can be used as a data source for different frameworks? .csv, .xml, .text etc 
  2. What are listeners in selenium? 

Listeners actually is an interface, that modifies the behavior of the system. It is used for  customization of reports. 2 types webdriver listeners, TestNg Listeners. 

  1. How do you take screenshots in selenium  

webdriver? takescreenshot function 

  1. What do you mean by assertions in  

selenium? Assert, verify, wait for 

  1. How many phases are there in maven build cycle? 

6 validate-compile-test-package-install-deploy 

  1. How will you handle keyboard and mouse related action  

using selenium? By action class, robot class, venium driver 

  1. What do you mean by WebDriver? 

Webdriver is an interface which is used to automate api of browser for testing. 15. How do you handle drag and drop option? Using action classes 

  1. How you handle java pop-ups in selenium? 
  2. Using alert, switch to alert, accept, dismiss, get text. 
  3. What does means Public static void main(variable,value) 

Public/private/protected/default-Access specifier Static- modifier 

Void- return type Main-class name 

  1. How to input text into a text box without Sendkeys? JavascriptExecuter  executor = (JavascriptExecutor)driver;  executor.excuteScript(“document.getElementById(“<<inputbox_id>>”).value =’new value’);

 

  1. What are the open source frameworks supported by  

selenium webdriver? TestNG, Junit, Cucumber, Robot  

Framework, Appium, Protractor. 

  1. How to handle hidden elements in selenium webdriver?  JavascriptExecuter js = (JavascriptExecutor)driver;  js.excuteScript(“document.getElementById(“<<displayed_text>>”).value 

=’Hiddentext); 

  1. How to handle iframes in selenium webdriver?  

driver.switchTo().frames(via index value, name,  

webelement );  

driver.findeElement(by.id(“value”)).getText();  

driver.switchTo().defaultContent();-To get back from  

iframe 

  1. How you handle dropdown values? 

From select class, via visible text, value, index 

  1. How to get color of webelement using  

selenium webdriver? First get the locator of  

webElement , then get 

String color= object.getCssValue(“background-color”) 

String HexbackColor= color.fromString(color).asHex(); 

It will give you RGb codes , you need to convert them into back color using HEX function 25. How you handle alert in selenium webdriver? 

Simple alert(one option), Confirm Alert(Y/N), Prompt  

alert(enter any value) Alert a= driver.switchTo().alert(); 

a.getText(); 

a.accept(), a.dismiss(), a.sendKeys(“name”); 

  1. How you handle multiple windows tabs in  

selenium webdriver? String  

PID=driver.getWindowHandle(); 

Set<String> allWindowHandle= driver.getWindowHandles(); 

Apply for loop on allWindowHandle -> switchTo().window(Id); ->if(!(Id.equals(PID)) - >driver.close(); 

===================================

 

JAVA ONE LINE CONCEPTS 

  1. java file mai ek hi public class hoti hai, uske alava aur classes v ho sakti hai par  public ek hi. 
  2. If we need to create one variable for multiple values, we need to use Array concept. 3. Int marks[] = new int[5] 
  3. Array can store only homogenous data, int for int array, string for string, 5. If we need to add heterogeneous data in array, we need to create object array. 6. Object a[] = new Object[5]; now we can add different data type objects. 7. Array is fixed in size, which we define while creating. 
  4. If we try to access index value >= given index value, we got  arrayOutOfBundException. 
  5. Arrays are not defined by any data layer structure so we can’t run readymade  methods on it. 
  6. To overcome this, we have collection framework under which there are  ArrayList, List, HashMap, HashTable, Tree, Stack. 
  7. We can add new elements in run time under collections while in array we cannot. 12. Collection is a group of objects. To represent this we need certain interfaces and  classes. 
  8. Common operations we generally do on collections are adding objects, removing objects & finding object. 
  9. Collection (I) is called collection interface having methods which are common  throughout all collections. 
  10. Collections is basically a class from java.util package which contains some  methods which we can use for collection objects. 
  11. Collection – 1. List, 2. Set, 3. Queue 
  12. List (I) is child of collection(I). In list Insertion order is preserved and duplicates are  allowed. 
  13. ArrayList, LinkedList, Vector these are different classes which implements List  Interface
  14. Set(I) is child of collection(I). Insertion order is not preserved & duplicates not  allowed. 
  15. HashSet, Linked Hashset these are different classes which implements Set  Interface
  16. Queue(I) is child of collection(I). We used it when we need prior to processing  means first in first out concept. 
  17. priorityQueue is class which implements Set Interface. 
  18. There is one independent interface known as Map(I). In Map(I) objects are created  with key and value pair. Key cannot be duplicate, but Value can be. 
  19. Hashmap, Linked Hashmap, Hash Table these are different classes which  implements Map 

Interface. 

  1. Whatever methods present in Collection(I) are also present in their child interface  i.e List, Set, Queue.
  1. add(object o), addAll(Collection c), remove(Object o),  removeAll(Collection c), retainAll(Collection c) these are some  methods of Collection Interface. 
  2. clear(), isEmpty(), size(), contains(), conatinsAll(), toArray() are also some  methods. 
  3. In List index play an important role because with the help of index only we  can find duplicates elements. 
  4. add(index , object), get(index), set(index, object) are methods of List Interface. 30. ArrayList al= new ArrayList(), it allows heterogenous objects also. 
  5. ArrayList<Str> al= new <str>(), now it can store objects of string only. 32. Collections.Sort(al) , Collections.Shuffle(al) This will sort & shuffle the objects of  arraylist. 
  6. We can read the data with for loop, for each loop, iterator () method. 
  7. JVM have 2 types of memories Static pool -static data, heaps-Non static data,

 

COLLECTION FRAMEWORK 

  1. A collection represents a group of objects. 
  2. Java collections provide classes and Interfaces for us to be able to write code. 3. We need collections for efficient storage and better manipulation of data in java. 4. Collection reduces programming effort, provide in-build methods and classes. 5. ArrayList -> For variables size collections 
  3. Set -> For distinct collection 
  4. Stack(queue)-> A LIFO (Last In First Out) data structure 
  5. HashMap -> For strong key - value pairs 
  6. Iterator- To iterate the element from collection. 
  7. Collections class is available in java util package collection class also provides static  methods for sorting, searching. 
  8. Common methods available in Collection are add(), addAll(), remove(),  removeAll(), size(), clear(), contains(), containsAll(), retain(), retainAll() 
  9. Common exception is collections are NullPointerException,  ClassCastException, IllegalargumentException, IllegalStateException,  UnsupportedOperationException

 

  1. Thread Safety-When multiple threads are working on same data, and the  value of our data is changing, that scenario is not thread-safe and we will  get inconsistent results. When a thread is already working on an object and  prevent another thread on working on the same object is known as thread  safety. We can achieve Thread safety via Synchronization, Volatile  Keyword, Atomic variable, Final Keyword. 
  2. Array List: 
  • ArrayList<Object Type> ar = new ArrayList<Object Type>(); 
  • ArrayList is Dynamic in nature. 
  • Virtual Capacity of ArrayList by default is 10 but Physical capacity if we did not add any  object is 0. Once we start adding Physical objects Virtual Capacity got decreased by  same. 
  1. Hashmap: 
  • Hashmap<String, String>capitalmap = new Hashmap<String,  

String>(); capitalmap.put(“India”, “New Delhi”);

 

MAVEN INTERVIEW QUESTIONS 

  1. What is Maven: 
  • Maven is a project management tool that is based on POM (project object model). It is  used for projects build, dependency and documentation. 
  • It simplifies the build process. 
  1. Why Maven Required 

Maven project eliminates the Adding set of Jars in each  

project. It Creates write Project Structure. 

Building and Deploying the project is very simple. 

  1. What is Build Tool 

A build tool takes care of everything for building a process. It does following: • Generates source code 

  • Compiles source code 
  • Packages compiled code into JAR of ZIP file 
  • Installs the packaged code in local repository, server repository, or central repository 
  1. How to install Maven in Window machine 
  • Download maven and extract it 
  • Add JAVA_HOME and MAVEN_HOME in environment variable 
  • Add maven path in environment variable 
  • Verify Maven apache 

maven-3.5.0-bin.zip 

  1. Verify maven

 

To verify whether maven is installed or not, open the command prompt and write: mvn −version 

Maven home: E:\apache-maven\apache-maven-3.3.9\bin 

Java version: 1.8.0_102, vendor: Oracle Corporation 

Java home: C:\Program Files\Java\jdk1.8.0_144\bin 

  1. Maven Repository 

There are 3 types of maven repository: 

  • Local Repository 
  • Central Repository 
  • Remote Repository 

Maven searches for the dependencies in the following order: Local repository then  Central repository then Remote repository. Local Repository: Means .m2 folder in  your system 

Central Repository: Maven central repository is located on the web. It has been  created by the apache maven community itself 

Remote Repository: Company Specific Library or Custom Library

<project
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com</groupId>
	<artifactId>Cucumber</artifactId>
	<version>0.0.1</version>
	<packaging>jar</packaging>
	<name>selenium</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>3.5.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

 

Project: It is the root element of pom.xml file 

Model Version: It is the sub element of project. It specifies the model Version. It should  be set to 4.0.0 

Group Id: will identify your project uniquely across all projects (com.test.selenium) Artifact Id: project name 

Packaging: defines packaging type such as jar, war etc. 

Dependencies: defines dependencies for this project. 

Dependency: defines a dependency. It is used inside dependencies. 

Scope: defines scope for this maven project. It can be compile, provided, runtime,  test and system.

 

  1. Maven Life Cycle 
  • validate - validate the project is correct and all necessary information is available • compile - compile the source code of the project 
  • test - test the compiled source code using a suitable unit testing framework. These  tests should not require the code be packaged or deployed 
  • package - take the compiled code and package it in its distributable format, such as a  JAR. 
  • verify - run any checks on results of integration tests to ensure quality criteria are met • install - install the package into the local repository, for use as a dependency in other  projects locally 
  • deploy - done in the build environment, copies the final package to the remote  repository for sharing with other developers and projects. 

mvn deploy:deploy-file -DgroupId=<group-id> \ 

-DartifactId=<artifact-id> \ 

-Dversion=<version> \ 

-Dpackaging=<type-of-packaging> \ 

-Dfile=<path-to-file> \ 

-DrepositoryId=<id-to-map-on-server-section-of-settings.xml> \ 

-Durl=<url-of-the-repository-to-deploy> 

===================================================================

 

JAVA HASHMAP INTERVIEW QUESTIONS 

1.How does put() method of HashMap works in Java? On hashing principle of key value  pair 

  1. What is the requirement for an object to be used as key or value in HashMap? 3. What will happen if you try to store a key which is already present in HashMap? 4. Can you store a null key in Java HashMap?
  2. Can you store a null value inside HashMap in Java?
  3. How does HashMap handle collisions in Java?
  4. Which data structure HashMap represents?
  5. Which data structure is used to implement HashMap in Java?
  6. Can you store a duplicate key in HashMap? (answer)
  7. Can you store the duplicate value in Java HashMap? (answer)
  8. Is HashMap thread-safe in Java?

12.What will happen if you use HashMap in a multithreaded Java application? 13.What are the different ways to iterate over HashMap in Java? 

  1. How do you remove a mapping while iterating over HashMap in Java?
  2. In which order mappings are stored in HashMap?
  3. Can you sort HashMap in Java? (answer)
  4. What is the load factor in HashMap? A load factor is a number that controls the resizing of HashMap when a number of elements in the HashMap cross the load factor as if the load factor is 0.75 and when becoming more than 75% full then resizing trigger  which involves array copy. 
  5. How does resizing happens in HashMap? (answer)
  6. How many entries you can store in HashMap? What is the maximum limit? 20.What is the difference between the capacity and size of HashMap in Java? 21.What will happen if two different keys of HashMap return the same hashcode()? =========================================

String one line que. 

java.lang.String class is used to create a string object. 

Different String methods: 

  • compareTo - The Java String compareTo() method is used for comparing two strings  lexicographically. 
  • boolean equals() - The java string equals() method compares the two given strings  based on the content of the string (case sensitive) 
  • String concat() – concat two strings 
  • boolean equalsIgnoreCase() - The java string equals() method compares the two given  strings based on the content of the string (not casesensitive) 
  • char charAt() – index position - The java string charAt() method returns a char value  at the given index number. 
  • boolean contains() 
  • toUpperCase() – convert to upper case 
  • toLowerCase() – convert to lower case

 

  • trim() – remove spaces from both sides of string 
  • substring() -- returns part of string 
  • boolean endsWith() 
  • boolean startWith() – ends with specified suffix or not 
  • int length() 
  • replace() 
  • int num = Integer.parseInt(str);- Convert String to int using Integer.parseInt(String) int num = Integer.valueOf(str);- Convert String to int using Integer.valueOf(String) Convert int to String using  

String.valueOf() String int ivar = 123; 

String str = String.valueOf(ivar);  

System.out.println("String is: "+str);  

System.out.println(555+str); 

  • Convert int to String using Integer.toString() 

int ivar = 123; 

String str = Integer.toString(ivar); 

System.out.println("String is: "+str); 

System.out.println(555+str); 

  • In java, string objects are immutable. Immutable simply means unmodified or  unchangeable.Once string object is created its data or state can't be changed but a new  string object is created. 

====================================================================== Array one line que. 

  • Write down syntax of iterator function?  

Iterator<String> it = studentList.iterator();  while(it.hasNext()){ System.out.println(it.next()); 

  • How to find max min of an unsorted array? 

MAX 

public class maxmin {

    public static void main(String[] args) {
        int[] arr = {
            1,
            45,
            67,
            98,
            455,
            678
        };

        int max = Integer.MIN_VALUE;

        for (int element: arr) {
            if (element > max) {
                max = element;
            }
        }

        System.out.println(“Max element is " + max); 
    }

}

 

MIN 

public class maxmin {

    public static void main(String[] args) {
        int[] arr = {
            1,
            45,
            67,
            98,
            455,
            678,
            -6
        };

        int min = Integer.MAX_VALUE;

        for (int element: arr) {

            if (element < min) {

                min = element;

            }

        }

        System.out.println(“Min element is " + min);

    }
}


========================

1.
How to reverse any array?

public class reverse array {
    public static void main(String[] args) {
        int[] arr = {
            1,
            45,
            67,
            98,
            455,
            678
        };
        int l = arr.length;

        int n = Math.floorDiv(l, 2);
        int

        temp;

        for (int i = 0; i < n; i++) {
            temp = arr[i];
            arr[i] = arr[l - i - 1];
            arr[l - i - 1] = temp;
        }

        for (int element: arr) {
            System.out.print(element + " ");
        }
    }
}

 

================================================================ public class reverse array { 

public static void main(String[] args) { int [] Array ={7,8,9,3,4,6,11,67,98};  int k=Array.length-1; for(k=Array.length-1;k>=0;k--){ 

System.out.print( Array[k] + " "); 

}} 

================================

  1. How to remove duplicate elements from ArrayList? we can handle this scenario via  LikedHashSet 

ArrayList<Integer> numbers = new  

ArrayList<Integer>(Arrays.asList(1,2,2,4,6,7,2,3,5,4,3,8,2,8)); LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(numbers); ArrayList<Integer>  numbersListWithoutDuplicate = new ArrayList<Integer>(LinkedHashSet));  System.out.println(numbersListWithoutDuplicate);

 

Also we can handle this via stream 

ArrayList<Integer> marksList = new 

ArrayList<Integer>(Arrays.asList(1,2,2,4,6,7,2,3,5,4,3,8,2,8)); List<Integer>  marksListUnique= marksList.stream().distnict().collect(Collectors.toList()); System.out.println(marksListUnique); 

  1. How to compare two array list? Via Collection.sort(); and equal 
  2. How to find additional element in list while comparing 2 List? If we have 2 list l1 & l2 , first we remove all element of l2 

L1.removeAll(l2): 

Sysout(L1) – you will get additional element. 

  1. How to find common element in list while comparing 2 List? L1.retainAll(L2); 

Sysout(L1) – you will get common element. 

  1. How will you print length of string without using length method. String str = “Pankaj” 

Sysout(str.toCharArray().length); 

Sysout(str.lastIndexOf(“”)); 

  1. How to find missing element in integer array? 
  2. How to reverse a string?  
  3.  

String str = “Pankaj”; int len = str.length(); 

String rev = ” ” 

for(int i<len-1 , i>=0, i- 

-){ rev = rev +  

str.charAt(i); 

Sysout(rev); 

  1.  

Create a string-> create new stringBuffer and here you can apply reverse fuction. String str = “Pankaj”; 

StringBuffer sf = new  

StringBuffer(s);  

Sysout(sf.reverse()); 

  1. How will you remove special/junk char from string?  

We have to use regular expression [a-z, 0-9, A-Z] 

String str = “Y^%^*%&*^*(&*(Pankaj”;

FPT Software Academ – #Code Your Life 

Str= Str.replaceAll([^a-z, 0-9, A-Z], “”); 

Sysout(str); 

  1. How to reverse an Integer? 

int num = 12345; int rev = 0;  

while(num !=0){ 

rev =rev *10+ num %  

10; num = num/10; 

Sysout (rev) 

======== //How to handle alert in Selenium write the syntax. 

public boolean isAlertPresent() { 

try 

driver.switchTo().alert(); 

return true; 

catch (Exception e) 

return false; 

------------------------ @Test // How can you switch to alert in selenium. 

public void test4() { 

driver.switchTo().alert().accept(); 

driver.switchTo().alert().dismiss(); 

Alert text = driver.switchTo().alert(); 

System.out.println(text.getText()); 

------------------------ @Test // How can you switch to frame in selenium 

public void test5() {

 

driver.switchTo().frame(0); 

driver.switchTo().frame("frame"); 

driver.switchTo().frame(driver.findElement(By.xpath("//input[@title='Search']"))); driver.switchTo().defaultContent(); 

----------------------- @Test // How can you handle windows in selenium 

public void test6() { 

String pwindow = driver.getWindowHandle(); 

// To get the window handle of single parent window 

Set<String> allWindows = driver.getWindowHandles(); 

// To get the window handles of all open windows in  

browser. Iterator<String> allWindow =  

allWindows.iterator(); 

// Apply iterator method to iterate on open windows. 

String parentWindow = allWindow.next(); 

// getting the next window handle by using .next()  

method  

driver.switchTo().window(parentWindow 

); 

// After getting window handle switching to that  

window. String childWindow =  

allWindow.next();  

driver.switchTo().window(childWindow) 

; driver.switchTo().defaultContent(); 

// this command will get us back to parent window from child window.

------------------------- @Test // How to use waits in selenium 

public void test7() { 

// below one is implicit wait which is applicable for all the we elements driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

 

// below one is Explict wait syntax , first we need to create object of  WebDriverWait. 

WebDriverWait wait = new WebDriverWait(driver, 10); 

// here you can do your validation of your action whatever you want to check. 

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@title='Searc h']"))); 

---------------------------- @Test // How to mouse hover in selenium & drag drop 

public void test8() { 

// To do mouse hover & drag drop first we need to create object of  Actions class for web driver instance 

Actions act = new Actions(driver); 

// now we have to use moveToElement method of action  

class. //And to complete the action we need to use build &  

perform method 

act.moveToElement(driver.findElement(By.xpath("//input[@title='Search']"))).build().perform(); act.dragAndDrop(driver.findElement(By.xpath("Source")),driver.findElement(By.xpath("target"))); } 

------------------------------ @Test // How to select options from drop down 

public void test9() { 

// To select options from drop down first we need to create object of select  class 

Select sel = new Select(driver.findElement(By.xpath(""))); 

sel.selectByIndex(4); // to select item by index 

sel.selectByValue(""); // to select item by value 

sel.selectByVisibleText("text"); // to select item by visible  

text 

java.util.List<WebElement> allItems = sel.getOptions(); // To get all items of drop down 

----------------------------- @Test // How to get screenshots in selenium 

public void test10() {

 

// Directly we cannot take screenshots in selenium, we have to cast the  driver first with takescreenshot class 

File shot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Now you have to store file in your drive location. 

FileUtils.copyFile(shot, new File("D:\\shot1.jpg")); 

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

@Test // How to X & Y coordinates of window in selenium 

public void test11() { 

driver.manage().window().getPosition().getX(); 

driver.manage().window().getPosition().getY(); 

--------------------------- @Test // How you can count similar type of objects in web page. 

public void test12() { 

int size = driver.findElements(By.xpath("")).size(); 

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

@Test // How to execute java script in selenium? 

public void test13() { 

//Directly we cannot use Javascript executer in selenium, we have to cast the  driver first with Javascript executer class 

JavascriptExecutor jse =((JavascriptExecutor)driver); 

jse.executeScript("window.scrollBy(0,600)"); 

------------------------- @Test // How to read data from excel files using selenium? 

public void test14() {

 

Workbook workbook = WorkbookFactory.create(new FileInputStream(file)); Sheet sheet = workbook.getSheetAt(0); 

@Test // How to connect to database using selenium? 

public void test15() { 

DriverManager.getConnection(URL, "username", "password"); 

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

ABSTRACTION 

In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) in a  Page Class. We utilize these locators in tests, but we can’t see these locators in the tests.  Literally we hide the locators from the tests. 

Abstraction is the methodology of hiding the implementation of internal details and  showing the functionality to the users. 

INTERFACE 

Basic statement we all know in Selenium is WebDriver driver = new FirefoxDriver(); 

WebDriver itself is an Interface. So based on the above statement WebDriver driver = new  FirefoxDriver(); we are initializing Firefox browser using Selenium WebDriver. It means we are  creating a reference variable (driver) of the interface (WebDriver) and creating an Object. Here  WebDriver is an Interface as mentioned earlier and FirefoxDriver is a class. 

An interface in Java looks like 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. 

INHERITANCE 

We create a Base Class in the Framework to initialize WebDriver interface, WebDriver waits,  Property files, Excels, etc., in the Base Class. 

We extend the Base Class in other classes such as Tests and Utility Class. Extending one  class into other class is known as Inheritance. 

POLYMORPHISM

Combination of overloading and overriding is known as Polymorphism. We will see both  overloading and overriding below. 

Polymorphism allows us to perform a task in multiple ways. 

METHOD OVERLOADING

 

We use implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use  different time stamps such as SECONDS, MINUTES, HOURS etc., 

A class having multiple methods with same name but different parameters is called Method Overloading METHOD OVERRIDING 

We use a method which was already implemented in another class by changing its parameters. To  understand this you need to understand Overriding in Java. 

Declaring a method in child class which is already present in the parent class is called Method  Overriding. Examples are get and navigate methods of different drivers in Selenium. 

ENCAPSULATION 

All the classes in a framework are an example of Encapsulation. In POM classes, we declare the data  members using @FindBy and initialization of data members will be done using Constructor to utilize  those in methods. 

Encapsulation is a mechanism of binding code and data together in a single unit. I would like to discuss some other topics which we use in Automation Framework. WEB ELEMENT: 

Web element is an interface used to identify the elements in a web page. 

WEBDRIVER: 

WebDriver is an interface used to launch different browsers such as Firefox, Chrome, Internet Explorer,  Safari etc., 

FIND BY: 

FindBy is an annotation used in Page Object Model design pattern to identify the elements. FIND ELEMENT: 

Find Element is a method in POM to identify the elements in a web page. 

How to find duplicate char using hashmap? 

Find the count of char using hashmap?

 

Top 7 Selenium Commands with Details 

#1) get() Methods 

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

driver.getClass(); 

driver.getCurrentUrl(); 

driver.getPageSource(); 

driver.getTitle(); 

driver.getText(); 

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

getAttribute("value"); 

driver.getWindowHandle(); 

#2) Locating links by linkText() and partialLinkText() 

driver.findElement(By.linkText(“Google”)).click(); 

driver.findElement(By.partialLinkText(“abode”)).click(); 

#3) Selecting multiple items in a drop dropdown 

// select the multiple values from a dropdown 

Select selectByValue = new Select(driver.findElement(By.id("SelectID_One")));  selectByValue.selectByValue("greenvalue"); - By Value  selectByValue.selectByVisibleText("Red"); - By Visible Text  selectByValue.selectByIndex(2); - By Index 

#4) Submitting a form 

// submit the form  

driver.findElement(By.<em>id</em>("submit")).submit(); 

#5) Handling iframes 

Select iframe by id 

driver.switchTo().frame(“ID of the frame“); 

Locating iframe using tagName 

driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0)); Locating iframe using the index:

 

a)frame(index)  

driver.switchTo().frame(0); 

b)frame(Name of Frame) 

driver.switchTo().frame(“name of the frame”); 

c)frame(WebElement element) Select  

Parent Window 

driver.switchTo().defaultContent(); 

#6) close() and quit() methods 

driver.close(); - closes only a single window that is being accessed by the WebDriver instance  currently 

driver.quit();- closes all the windows that were opened by the WebDriver instance 

#7) Exception Handling 

WebElement saveButton = driver.findElement(By.id("Save"));

try {
    if (saveButton.isDisplayed()) {
        saveButton.click();
    }
} catch (NoSuchElementException e) {
    e.printStackTrace();
}

#4) isEnabled() 

isEnabled() to Check Whether the Element is Enabled Or Disabled in the Selenium WebDriver. findElement(By, by) with sendKeys() to type in the form fields. 

findElement(By, by) with getText() to store value of targeted web element. 

Submit() to submit a web form. 

findElements(By, by) to get the list of web elements

List<WebElement> allChoices = dropDown.findElements(By.xpath(".//fruitoption")); 

findElements(By, by) with size() to verify if an element is present

Boolean checkIfElementPresent= driver.findElements(By.xpath("//input[@id='checkbox2']")).size()!= 0; pageLoadTimeout(timeUnit) to set the time for a page to load 

driver.manage().timeouts().pageLoadTimeout(500, SECONDS); 

implicitlyWait() to set a wait time before searching and locating a web element. driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS); 

untill() from WebdriverWait and visibilityOfElementLocated() from ExpectedConditions to wait

 

explicitly till an element is visible in the webpage.  

WebDriverWait wait = new WebDriverWait(driver, 10); 

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated  (By.xpath("//input[@id=’name’]"))); 

untill() from WebdriverWait and alertIsPresent() from ExpectedConditions to wait explicitly till  an alert appears. 

WebDriverWait wait = new WebDriverWait(driver, 10); 

WebElement element = wait.until(ExpectedConditions.alertIsPresent() 

); 

Select class for selecting and deselecting values from the drop-down in Selenium WebDriver.  WebElement mySelectedElement = driver.findElement(By.id("select")); 

Select dropdown= new Select(mySelectedElement);dropdown.selectByVisibleText("Apple"); 

navigate() to navigate between the URLs

driver.navigate().to("https://www.softwaretestinghelp.com"); 

driver.navigate().back(); 

driver.navigate().forward(); 

getScreenshotAs() to Capture the entire page screenshot in Selenium WebDriver. File shot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 

FileUtils.copyFile(shot, new File("D:\\ shot1.jpg")); 

moveToElement() from the Actions class to simulate mouse hover effect. 

Actions actions = new Actions(driver); 

WebElement mouseHover = driver.findElement(By.xpath("//div[@id='mainmenu1']/div")); actions.moveToElement(mouseHover); 

actions.perform(); 

dragAndDrop() from Actions class to drag an element and drop it on another element.

 

WebElement sourceLocator = driver.findElement(By.xpath("//*[@id='image1']/a")); WebElement destinationLocator = driver.findElement(By.xpath("//*[@id='stage']/li")); 

Actions actions=new Actions(driver); 

actions.dragAndDrop(sourceLocator, destinationLocator).build().perform(); 

switchTo() and accept(), dismiss() and sendKeys() methods from Alert class to switch to popup  alerts and handle them. 

Alert alert = driver.switchTo().alert(); 

alert.sendKeys("This Is Softwaretestinghelp"); 

alert.accept() 

getWindowHandle() and getWindowHandles() to handle Multiple Windows in Selenium WebDriver. String handle= driver.getWindowHandle(); 

Set<String> handle= driver.getWindowHandles(); 

for (String handle : driver.getWindowHandles()){ 

driver.switchTo().window(handle); 

getConnection() from DriverManager to start Database Connection. 

DriverManager.getConnection(URL, "username", "password" ) 

POI to read from the excel files. 

Workbook workbook = WorkbookFactory.create(new FileInputStream(file)); 

Sheet sheet = workbook.getSheetAt(0); 

Asserts using assertEquals(),assertNotEquals(), assertTrue() and assertFalse() to compare the  results. 

Assert.assertEquals(message, “This text”); 

Assert.assertNotEquals(message, “This text”); 

Assert.assertTrue(result<0); 

Assert.assertFalse(result<0);

 

Các câu hỏi về tính cách và định hướng trong tương lai

Trong phần cuối cùng của buổi tuyển dụng Automation Tester, bạn có thể gặp các câu hỏi về tính cách và định hướng tương lai. Bạn hãy cho nhà tuyển dụng thấy mình là người cầu tiến, có khả năng làm việc trong môi trường cộng tác cũng như có ý định làm việc lâu dài với công ty.

Automation Tester là nghề nghiệp triển vọng cho các bạn sinh viên IT tại Việt Nam. Các bạn hãy chuẩn bị thật kỹ những tình huống có thể xảy ra để vượt qua các vòng tuyển dụng Automation Tester một cách tốt nhất.


Tìm hiểu thêm: CÂU HỎI PHỎNG VẤN AUTOMATION TESTER (Tiếng Việt)
Tìm hiểu thêm: 100 câu hỏi và câu trả lời phỏng vấn về Selenium


Nguồn tài liệu:

  • FPT Software Academy
  • Anh Tester

    Đường dẫu khó chân vẫn cần bước đi
    Đời dẫu khổ tâm vẫn cần nghĩ thấu