Automation Selenium Testing

Share

Selenium Automation Testing Real world Interview Question and Answer

 

Question: – How to switch from frame to main window? With syntax.

Answer: – We can give frame name, id, index and WebElement locator for identification

  1. Syntax

driver.switchTo().frames();                  // Switch to window to frame

driver.switchTo().defaultContent();  // Switch to Frame to window

  1. If we know the total number of frames in the web page, then we can use “index”. Index values help to easily switch between frames. Index will start from Zero i.e. if web page has only one frame then its index will be Zero.

         If we don’t know the number of frames the we can use “findElementBytabname()” method

        Syntax: –

                                      try

{

driver.switchTo().frame(indexnumber);

}

                                      catch(NoSuchFrameException e)

{

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

}

We have use try and catch if now frame will not available this throw exception  .      .  .          NoSuchFrameException()

  1. Use name as locater to find frame

Syntax: –

                  try

{

driver.switchTo().frame(“frameName”);

}

                    catch(NoSuchFrameException e)

{

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

}

  1. Use WebElement for switching frame

                Syntax: –

               try

{

WebElement button=driver.findElement(By.xpath(“”));

driver.switchTo().frame(button);

}

              catch (NoSuchFrameException e)

{

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

}

Question: -What is difference between (page object model) pom and pagefactory?

Answer: –

Page Object Model (POM)

Page Factory

POM is a Design pattern which segregate selenium code based on pages.

Ex: Create a separate java class for Login page , one more class for Home Page etc.

Advanced concept ( POM + new features )or

1. Elements are identified using @FindBy or @FindBys Annotation

2. Initialism all the elements declared in Point#1 at a time.

( in POM, initialization happens on the fly )

PageFactory.initElements(driver,this);

A Page Object Model is a way of representing an application in a test framework. For every ‘page’ in the application you create a Page Object to reference the ‘page’.

A Page Factory is one way of implementing a Page Object Model. In order to support the Page Object pattern, WebDriver’s support library contains a factory class.

 

Question: – What are challenges that you faced while automating test cases?

Answer: – Two types of challenges tester have to face one is technical and another is non-technical.

Technically

There are four common issues in test automation that are: –

  1. Wait time issues.

  2. Ifream issues

  3. Pop-up issues

  4. Issues in locating deeply nested elements.

Note: – Depend on which tool you are going to use/ using, the ways to solve might different.

Non-Technically

  1. Real Challenges comes in front of tester when client changes his requirement.

  2. Time pressure and Deadlines.

  3. Testing complete application.

  4. Automate everything

  5. Network unavailability

  6. Understanding company, client, and end-user expectations.

  7. Deciding when can testing should stop and how much testing coverage is enough.

  8. Find masked bugs.

  9. Receiving Management approval.

  10. Selecting and using the appropriate tools.

  11. Recognising a starting strategy.

  12. Making realistic expectations for automation.

 

Question: -There is a submit button in page it has id property. By using “id” we got “element not found expectation”, how will you handle this situation? What might be the problem in this case?

Answer: – In this situation, there are mainly two reasons that are:-

  1. ID is not matching

  2. ID is changing each time when load the page.

So to handle this situation instead of using find element by Id, we can use find element by Xpath.

Question: – If submit button contain in one of 3 frames in page, how will you handle this case?

Answer: – We can handle this problem by using SwitchTo() command.

 

Question: – If element is loaded by taking much time how to handle this situation in selenium.

Answer: – Using Wait can handle this situation in selenium.

 

Question: – What is the problem with Thread.Sleep in code?

Answer: – Theard.sleep() introduces a definite wait(that is fixed periods of inactivity) no matter what happens, which will slow down our test, and if you are using CI(Continuous integration) generally result take much time if we use it all over the place.

Secondly most people who use it end up doing so because they don’t understand a problem so it’s quick and easy to just throw in an arbitrary wait rather than trying to understand the problem and fix it.

For Example: – If we do an AJAX action and then have to wait for an element to appear, the correct thing to do would be to scan for the element until it appears, the correct thing to do would be to scan for the element until it appears and then carry on, but this is harder to code than to just throw in a 30 second wait so people use a Thread.seelp() instead.

Now the problem is that this means you don’t really know why the test has failed if the element is not picked up after your 30 second time out, is it because the element didn’t appear at all, or is it because the AJAX call took longer than normal to return?

If you had some code that scanned for the element you could stick in a much longer timeout secure in the knowledge that you are not slowing your test down, and also secure in the knowledge that when it fails you can be sure that it is because the element didn’t return.

I’m sure people will argue that it is easier to use Thread.sleep() and the difference in results as described above is not that great, but when you have 200 scripts getting run in CI and each one has about 5 Thread.sleeep() calls you’ll see how much pain just throwing in a Thread.sleep() can cause.

 

Question: – What is the concept of selenium grid?

Answer: – Selenium-Grid allows you run your 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. Essentially, Selenium-Grid support distributed test execution. It allows for running your tests in a distributed test execution environment.

 

Question: – When we execute test cases in grid where results will be stored in node or hub?

Answer: – Selenium and Grid is installed on hub, and they are not installed on nodes. Nodes contain only he jar files. So the result will be stored in hub

 

Question: – Difference b/w quit and close?

Answer: – close() command closes the Browser window which is in focus. If there are more than one Browser window opened by the Selenium Automation, then the close( ) command will only close the Browser window which is having focus at that time. It won’t close the remaining Browser windows.

Whereas quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

If Selenium Automation opens only single Browser window the close() and quit() commands work in the similar way. But when there are more than one Browser windows opened by the Selenium Automation they work differently.

 

Question: – Manually you opened a Firefox browser window with Gmail login, now with selenium you opened a Firefox browser window with Facebook login, what happens when we use quit method? Will it closes all windows including Gmail one?

Answer: – quit() command is used to close the focus browser basically quit() command shut down the WebDrivers instance and close all the Browser window which is having focus at that time.

So it will close only Firefox browser window with Facebook login.

 

Question: – What all annotations used in TestNG ?

Answer: – Total 15 annotations are used in TestNG

  1. @BeforeSuite: – The annotated method will be run only once before all tests in this suite have run.
  2. @AfterSuite: – The annotated method will be run only once after all tests in this suite have run.
  3. @BeforeClass: – The annotated method will be run only once before the first test method in the current class is invoked.
  4. @AfterClass: – The annotated method will be run only once after all the test methods in the current class have run.
  5. @BeforeTest: – The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
  6. @AfterTest: – The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
  7. @BeforeGroups: – The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
  8. @AfterGroups: – The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
  9. @BeforeMethod: – The annotated method will be run before each test method.
  10. @AfterMethod: – The annotated method will be run after each test method.
  11. @DataProvider: – Marks a method as supplying data for a test method. The annotated method must return an Object [ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
  12. @Factory: – Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].
  13. @Listeners: – Defines listeners on a test class.
  14. @Parameters: – Describes how to pass parameters to a @Test method.
  15. @Test: – Marks a class or a method as a part of the test.

 

Question: – If we want to do DataDriven with TestNG, which annotations required?

Answer:TestNG @DataProvider Annotation is required for DataDriven with TestNG. @DataProvider Annotation of TestNG framework provides us a facility of storing and preparing data set in method. Task of @DataProvider annotated method is supplying data for a test method. Means you can configure data set in that method and then use that data In your test method. @DataProvider annotated method must return an Object[][] with data.

 

Question: – Is it possible to pass test data through testng.xml file, if yes how?

Answer: – Yes it is possible to pass test data through XML file by using @Parameters annotations

To do so, you will need to

  • Create an XML file which will store the parameters
  • In the test, add annotation @Parameters

XML File

  • <?xml version=”1.0″ encoding=”UTF-8″?>
  • <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”>
  • <suite name=”TestSuite” thread-count=”3″ >
  • <parameter name=”author” value=”India” />
  • <parameter name=”searchKey” value=”USA” />
  • <classes>
  • <class name=”parameters.ParameterWithTestNGXML”>
  • </class>
  • </classes>
  • </test>
  • </suite>

Selenium Scripting

@Test

@Parameters({“author”,”searchKey”})

public void testParameterWithXML(@Optional(“ABC”)String author,String searchKey)throws InterruptedException{}

Note: -There are mainly two ways through which we can provide parameter values to test-methods: One is through testng.xml XML configuration file and through DataProviders.

Question: – How to run specific kind of Test cases using TestNG?

Answer: – Three ways we can run Test Cases using TestNG

  • On an existing testng.xml.
  • On a synthetic testng.xml, created entirely from Java.
  • By directly setting the test classes.

 

Question: – How to prioritize test cases in TestNG?

Answer: – In TestNG “Priority” is used to schedule the test cases.at is we can execute Test case in order.  In order to achive, we use need to add annotation as @Test(priority=??). The default value will be zero for priority.

If you don’t mention the priority, it will take all the test cases as “priority=0” and execute.

If we define priority as “priority=”, these test cases will get executed only when all the test cases which don’t have any priority as the default priority will be set to “priority=0”

 

Question: – What are all interfaces available in selenium?

Answer: –

Interface Description
Alert
Capabilities Describes a series of key/value pairs that encapsulate aspect of a browser
ContextAware Some implementations of WebDriver, notably those that support native testing, need the ability to switch between the native and web-based contexts.
HasCapabilities Used by classes to indicate that they can describe the capabilities they possess.
JavascriptExecutor Indicates that a driver can execute JavaScript, providing access to the mechanism to do so.
OutputType<T> Defines the output type for a screenshot.
Rotatable Represents rotation of the browser view for orientation – sensitive devices.
SearchContext
TakeScreenshot Indicates a driver that can capture a screenshot and store it in different ways.
WebDriver The main interface to use for testing, which represents an idealised web browser
WebDriver.ImeHandler
WebDriver.Options An Interface for managing stuff you would do in a browser menu
WebDriver.TargetLocator Used to locate a given frame or window.
WebDriver.Timeouts An interface for managing timeout behaviour for WebDriver instance
WebDriver.Window
WebElement Repersents an HTML element.

 

Question: – Action is class or interface?

Answer: – Action is an interface.

Use to perform Advanced User Interactions, like drag and drop, keyboard events; selenium came up with Action and Actions interface under a comprehensive API, named as Advanced User Interaction which facilitates user actions to be performed on an application. Thus users can use this API to simulate usage of keyboard or mouse events.

Example:-

  • To double-click a control we have DoubleClick(), method of Actions Class.

  • To Send keyboard actions, we have SendKeys() ,method.(Equivalent to WebElement.sendKey(…))

  • Clicking the mouse button that brings up the contextual menu.we can use “ContextClick()”, method.

Package:-

import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

Syntax:-

Actions oAction=new Actions(selenium);

oAction.contextClick(element).perform();

 

Question: – Why we using TestNG? What are benefits we get using TestNG? Can we execute test cases in order without using TestNG?

Answer: – WHY We Using TestNG

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionality that make it more powerful and easier to use, such as:

  • Run your tests in arbitrarily big thread pools with various policies available (all methods in their own thread, one thread per test class, etc…).

  • Test that your code is multithread safe.

  • Flexible test configuration.

  • Support for data-driven testing (with @DataProvider).

  • Support for parameters.

  • Powerful execution model (no more TestSuite).

  • Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc…).

  • Embeds BeanShell for further flexibility.

  • Default JDK functions for runtime and logging (no dependencies).

  • Dependent methods for application server testing.

TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc…

Advantages of TestNG

  • TestNG allows us to execute of test cases based on group.

  • TestNG annotations are easy to understand.

  • Parallel execution of selenium test cases is possible in TestNG.

  • Three kinds of report generated.

  • Order of execution can be change using TestNG

  • Failed test cases can be executed.

  • Without having main function we can execute the test method.

  • An xml file can be execution order and we can skip the execution of particular test case.

Can we execute test cases in order without using TestNG

 Yes, we execute test cases in order without using TestNG with the help of Junit

 

Question: – Explain polymorphism in java.

Answer: – Polymorphism means ‘many forms’. In OOP, polymorphism means a type can point to different object at different time. In other words, the actual object to which a reference type refers can be determined at runtime.

In Java, polymorphism is based on inheritance and overriding.

Polymorphism is a robust feature of OOP. It increases the reusability, flexibility and extensibility of code.

 

Question: -There are two methods in same class with same name with different arguments and different access modifiers like

 public void m1(int a){}

 private void m1(string b){}

 Is it overloading or not?

Answer: – Overloading allows different methods to have same name, but different signatures where signature can differ by number of input/output parameters or type of input/output parameters or both.

So yes this is overloading.

 

Question: – What are types of inheritance in java?

Answer: -Single Inheritance, Multi-Level Inheritance and Hierarchical Inheritance.

 

Question: – Is multiple inheritance is possible in java? Reasons?

Answer: – To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

 

Question: – Is multilevel inheritance is possible in java? Give reason.

Answer: – A class can implement multiple interfaces. Object class is not an example of multiple inheritance. May be you misinterpreted the question. The answer is Java supports multi-level inheritance but not multiple inheritance.

 

Question: – There are 10 pages in same window; an image is present in any page out of ten pages in same window. How will you validate this scenario?

Answer: – Get the total numbers of frames on a webpage base on that have a for loop and switchTo() all frame one by one and check if image is present then come out of  that frame and again switch to next frame, continue this till you get image then break the loop.

Question: – How to check image is loaded correctly or not in page?

Answer:
WebElement image1 = driver.findElement(By.xpath(“//div[contains(@class,’global-header__brand’)]”));

Boolean imageLoaded1 = (Boolean) ((JavascriptExecutor)driver).executeScript(“return arguments[0].complete && typeof arguments[0].naturalWidth != “undefined” && arguments[0].naturalWidth > 0″, image1);

if (!imageLoaded1)

{

System.out.println(“1. Image is not present”);

}

else

{

System.out.println(“1. Got it”);

}

 

Question: – What is the purpose of Sikuli?

Answer: -Sikuli automates anything you see on screen using the image recognition method to identify GUI elements. Sikuli script allows users to automate GUI interaction by using screenshots.

 

Question: – Is it possible to compare two images with Sikuli?

Answer: – Yes

 

Question: – How to check webpage is fully loaded or not using Selenium?

Answer: – This situation can be solved by using JavaScript executors.

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript(“return document.readyState”).Equals(“complete”));

 

Question: – Write a code for DB connection.

Answer: – Creating SQL & MySQL Connections:

package util;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

public class DbManager

{

private static Connection con = null;

private static Connection conn = null;

// Database connection for SQL Server

public static void setDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try{

Class.forName(TestConfig.driver);

con =   DriverManager.getConnection(dbConnectionUrl, dbUserName, dbPassword);

if(!con.isClosed())

System.out.println(“Successfully connected to SQL server”);

}catch(Exception e){

System.err.println(“Exception: ” + e.getMessage());

}       }

public static void setMysqlDbConnection() throws SQLException, ClassNotFoundException, AddressException, MessagingException

{

try

{

Class.forName (TestConfig.mysqldriver).newInstance ();

conn = DriverManager.getConnection (mysqlurl, mysqluserName, mysqlpassword);

if(!conn.isClosed())

System.out.println(“Successfully connected to MySQL server”);

}

catch (Exception e)

{

System.err.println (“Cannot connect to database server”);

}

}

// Query list for SQL

public static List<String> getQuery(String query) throws SQLException

{

Statement St = con.createStatement();

ResultSet rs = St.executeQuery(query);

List<String> values = new ArrayList<String>();

while(rs.next()){

values.add(rs.getString(1));

}

return values;

}

// Query list for MySQL

public static List<String> getMysqlQuery(String query) throws SQLException

{

Statement St = conn.createStatement();

ResultSet rs = St.executeQuery(query);

List<String> values1 = new ArrayList<String>();

while(rs.next()){

values1.add(rs.getString(1));

}

return values1;

}

 

Question: – How do you handle exception handling in selenium?

Answer: – Same Try Catch like used in java.

 

Question: – Explain run time and compile time polymorphism.

Answer: – Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type.

Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.

Compile time Polymorphism Run time Polymorphism
In Compile time Polymorphism, call is resolved by the compiler. In Run time Polymorphism, call is not resolved by the compiler.
It is also known as Static binding, Early binding and overloading as well. It is also known as Dynamic binding, Late binding and overriding as well.
Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature and different return type. Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.
It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
It provides fast execution because known early at compile time. It provides slow execution as compare to early binding because it is known at runtime

 

Question: – Write a code for multiple handling windows?

Answer: –

public void test() throws Exception {
// Opening site
driver.findElement(By.xpath(“//img[@alt=’SeleniumMasterLogo’]”)).click();
// Storing parent window reference into a String Variable
String Parent_Window = driver.getWindowHandle();
// Switching from parent window to child window
for (String Child_Window : driver.getWindowHandles())
{
driver.switchTo().window(Child_Window);
// Performing actions on child window
driver.findElement(By.id(“dropdown_txt”)).click();
List  dropdownitems=driver.findElements(By.xpath(“//div[@id=’DropDownitems’]//div”));
int dropdownitems_Size=dropdownitems.size();
System.out.println(“Dropdown item size is:”+dropdownitems_Size);
((WebElement) dropdownitems.get(1)).click();
driver.findElement(By.xpath(“//*[@id=’anotherItemDiv’]”)).click();
}
//Switching back to Parent Window
driver.switchTo().window(Parent_Window);
//Performing some actions on Parent Window
driver.findElement(By.className(“btn_style”)).click();
}

 

Question: -How do you handle synchronization in selenium?

Answer: – By using wait we can handle synchronization in Selenium.

 

Question: – Why do we need Software Testing Metrics?

Answer: – Metrics provide insight into the project’s status in relation to predefined goals.    It is important to measure the efficiency and effectiveness of the Test processes. Without metrics, how would you know that everything is right OR something needs your attention!

  • Helps in decision-making for next phase of activities, process or technology change.

  • Easy for management to digest one number and drill down, if required.

  • Different Metric(s) trends act as monitor when the process is going out-of-control.

  • Evidence of the claim or prediction.

  • Help us judge how efficient the testing efforts are.

  • Make proactive and informed decisions

 

Question: – 7 Soft skills every ‘QA Tester’ needs:

Answer:

  1. Know how to ask the right questions, and when to ask them

  2. Know how to listen

  3. Know how to focus on what business stakeholders care about … and forget the rest

  4. Know how to play well with others: Take a developer to lunch

  5. Know how to deal with bullies

  6. Know how to manage your time effectively

  7. Know how to trust your judgment — and your intuition

 

Question: – What is the most challenging situation you have had in your Testing experience?

Answer: – As you might have guessed, it depends on each tester’s experience. The challenge can be technical, process-oriented, people’s related, domain specific OR anything within your Testing experience. For me,

  • Testing a technically-challenging application such as social-connected applications, application involving multiple third-party interfaces, cloud-big data-IoT-Analytics-etc. applications.

  • Maintaining a balance between design/execution efficiency and defect detection. Improving the Test coverage. Sticking to agile principles.

  • Resources on unplanned leaves, some even abscond. Estimation gone wrong, requiring weekend & extended working hours. Rating discussions with unhappy employees.

  • A team of fresher’s with limited domain knowledge. Planning for knowledge transfer sessions. The thumb rule – be realistic & tell your genuine challenges!

 

Question: – What is Automation and Manual Testing?

Answer: –

  • Automation: Software testing method which uses automation software, tools and scripts to run tests that repeat predefined actions, matches the developed program’s probable and real results.

  • Manual: The process of manual software testing involves manually running the individual tests or tasks associated with a product without the aid of scripts or other tools, in order to identify bugs or other issues. During this process, the testing team will use the application from end-user perspective.

 

Question: – How generate user defined exceptions, write syntax?

Answer: –

class MyException extends Exception

{

String s1;

MyException(String s2)

{      s1 = s2;   }

@Override

public String toString()

{

return (“Output String = “+s1);

}

}

public class NewClass

{

public static void main(String args[])

{

try

{

throw new MyException(“Custom message”);

}

catch(MyException exp)

{

System.out.println(exp);     ‘

}

}

}

 

Question: – Difference between throw and throws keyword?

Answer: –

throw throws
Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

 

8 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *