Thursday 22 March 2018

General Selenium Automation Interview Questions

Selenium Automation is very popular trends in software testing industry. I have seen many articles in internet for interview questions. There is no any sure interview questions. It is all depends on interviewer.

I have prepared some interview questions for Selenium Automation only. If I am interviewer then i will ask that types of questions for sure.

I have added answers of question if I already added in my blog. If not then I will add later once I added in my blog.


1. Explain basic idea of selenium.
Ans : Selenium Basics


2. Explain me selenium automation project you worked. 



3. How to create hybrid framework using Data Driven and Keyword Driven framework?



4. How to use POM in selenium?
Ans : Page Object Model (POM) Framework in Selenium



5. Write java program for below definition.

If I enter number 5 then output should be as below.

5*5 - 4*4 + 3*3 - 2*2 + 1*1

If I enter 4 then

4*4 - 3*3 + 2*2 - 1*1

Ans : Java Program For Number Series

6. Write java program for below definition.

If I enter String 'aabbccddefgh' the output should be as below.

Output = 2a2b2c2d1e1f1g1h

Ans : Java Program For String Example

7. Explain difference between Implicit Wait and Explicit Wait.
Ans : Implicit Wait Vs. Explicit Wait Vs. Fluent Wait

8. How many element locators is there in selenium.
Ans : Different Locators in Selenium

9. Write Xpath for select element highlighted span tag in below HTML code.

<div>
 <span>Test</span>
  <span>Test1<span>
</div>
<span>ABC</span>
<div>
 <span>Test</span>
  <span>Test2<span>
</div>
<span>ABC</span>
<div>
 <span>Test</span>
  <span>Test3<span>
</div>
<span>ABC</span>
<div>
 <span>Test</span>
  <span>Test4<span>
</div>
<span>ABC</span>

Ans : 
Xpath = "//div[span/span[text() = 'Test3']]/following::span[text() = 'ABC']" 

10. How to maximize chrome browser directly when you initiate Webdriver instance. It should be open in maximize mode.
Ans : 
You can open chrome browser directly using capabilities when initiate webdriver instance. Please go to below link for how to use capabilities.
How to Set Capabilities and Proxy Setting for Webdriver

11. How to initiate Firefox browser for Firefox version grater than 48.
Ans : 
You have to use 'GeckoDriver' for Firefox version grater than 48. It means you have to set System property same as chrome browser with GeckoDriver.

System.setProperty("webdriver.gecko.driver", "Path of Gecko Driver");
WebDriver driver = new FirefoxDriver();


12. What is Maven in selenium?

13. Did you ever integrate Jenkins with selenium? If yes then explain how to integrate.

14. How many ways you can generate test result report?
Ans : There is many ways to generate test result report in selenium. Below is different ways to generate result report.

  • TestNG report (Auto generate when you use TestNG)
  • JUnit Report
  • Ant report
  • Excel report (You have to write code for this)
  • CSV report (You have to write code for this)
  • HTML Report using Extent report) - Go to this link Extent Report for Extent Report.

15. How to Handle browser based Popup in selenium?
Ans : How to Handle PopUp in Selenium

16. How to Handle Windows in selenium?
Ans : How to Handle Windows in Selenium

17. How to Handle Windows based Popup in selenium?
Ans : Handle Windows Based Popup

18. How to do SQL database connection in selenium?

Ans : How to Do Database Connection in Selenium

19. How to handle below scenario without using Implicit and Explicit wait. You can use Thread.sleep() function.

Scenario : I have one element on page and every time it will take different time to load on page. some time 1 sec, some time 5 sec and some time 8 sec. I want to click on that element. Maximum time you have to wait for that element is 10 sec. If element do not appear after 10 sec than throw exception otherwise click on that element.

Ans : How Handle Wait Without Using Explicit and Implicit Wait in Selenium

20. How to Highlight Element when you perform click on that element.
Ans : How to Highlight Element in Selenium


Please add comment if you have any questions.


How Handle Wait Without Using Explicit and Implicit Wait in Selenium

Suppose you have one element on page and every time it will take different time to load on page. some time 1 sec, some time 5 sec and some time 8 sec. I want to click on that element.
Maximum time you have to wait for that element is 10 sec. If element do not appear after 10 sec than throw exception otherwise click on that element.

We need to use Thread.Sleep() function for this scenarios.

I have created below function for handle this scenario.

    public boolean mWaitAndClick(WebDriver driver, WebElement vElement) throws Exception
    {
     boolean bWaitAndClick = true;
        int MAXIMUM_WAIT_TIME = 10;  // this is seconds               
        int counter;
        
        try
        {
   vElement.click();
 }
        catch (Exception E) 
        {         
   for(counter=1; counter<=MAXIMUM_WAIT_TIME; counter++)
   {
    try
          {
     vElement.click();
     
     bWaitAndClick = true;     
     
     break;
          }
          catch(Exception e)
          {
           Thread.sleep(1000);
          }
   }
   
   if(counter>10)
   {
    bWaitAndClick = false;    
    throw new Exception("Element not found");    
   }
   
 }
        
        return bWaitAndClick;        
    }





Java Program For Number Series

If I enter number 5 then output should be as below.

Output = 5*5 - 4*4 + 3*3 - 2*2 + 1*1

If I enter 4 then

Output = 4*4 - 3*3 + 2*2 - 1*1

Below is code.

First Method : 

public class JavaExampleSeries 
{
 
 public static void main(String[] args)
 {
  int number = 5;
  long output = 0;
  int counter = 1;  
  
  if(number%2==0)
  {
   for(int i=number; i>=1; i--)
   {
    if(counter%2==0)
    {
     output = output - i*i;
    }
    else
    {
     output = output + i*i;
    }
    counter++;
   }
  }
  else
  {
   for(int i=number; i>1; i--)
   {
    if(counter%2==0)
    {
     output = output - i*i;
    }
    else
    {
     output = output + i*i;
    }
    counter++;
   }
   output = output+1;
  }
  
  System.out.println("Output is : " + output);
 }
 
}

Second Method :


public class JavaExampleSeries 
{
 
 public static void main(String[] args)
 {
  int number = 5;
  long output = 0;         
  int iterations = number/2;
  
  for(int i=1; i<=iterations; i++)
  {
   output = output + ((number*number)-((number-1)*(number-1)));
   
   number = number-2;   
  }
  
  if(number%2>0)
  {
   output = output+1;
  }
    
  System.out.println("Output is : " + output);  
 } 
}




Java Program For String Example

If I enter String 'aabbccddefgh' the output should be as below.

Output = 2a2b2c2d1e1f1g1h


public class JavaExampleString1 
{

 public static void main(String[] args)
 {
  String temp = "aabbccddefhg";
  String output = "";
    
  System.out.println(temp.length());
  System.out.println("Input String : " + temp);
  int vCounter = 1;
  for(int i=0; i<temp.length(); i++)
  {
   if(i<(temp.length()-1))
   {
    if(temp.charAt(i) == temp.charAt(i+1))
    {
     vCounter++;
    }
    else
    {    
     output = output + Integer.toString(vCounter) + temp.charAt(i);
     //System.out.println(output);
     vCounter = 1;
    }
   }
   else
   {
    output = output + Integer.toString(vCounter) + temp.charAt(i);
   }
      
  }
  
  System.out.println("Output String : " + output);

 }

}

Tuesday 20 March 2018

How to Read Configuration File in Selenium C#

When we are working on automation framework then we have to follow such strategy so we can avoid hard code value as much as we can.

There are many parameters in every framework we can be changed frequently for running test case on different environment as well as with different configuration. So, we can not use hard code value for such parameters. We have to use configuration file for this scenario.

In that file, we can store all the parameters which are used in framework like browser name, browser type, application URL etc. in Key-Value manner.

First of all you have to 'System.Configuration' assembly reference to access configuration settings, using ConfigurationManager.

You can add that assembly reference from right click in References then go to Assembles section and add it.



There are many methods for read configuration file.

First Method:

Suppose we have below 'app.config' file in project. We have only one section 'appSettings' and very simple app.config file.


<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <startup>  
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  </startup>  
  <appSettings>  
    <add key="BrowserName" value="Chrome"/>  
    <add key="BrowserType" value="local"/>
    <add key="URL" value="www.google.com"/>  
  </appSettings>  
</configuration>  

Now, you need to create one function for reading parameters in 'appSettings' section. I have created below function for that and I have used 'ConfigurationManager' for reading value.


public static void ReadConfigurationFile()  
    {  
        String browserName = ConfigurationManager.AppSettings["BrowserName"];  
        String browserType = ConfigurationManager.AppSettings["BrowserType"];
 String URL = ConfigurationManager.AppSettings["URL"];  
          
    }

You can use above function for reading values from configuration file.

Second Method:

Suppose we have below 'app.config' file in project. We have only one section 'ApplicationSettings' but we have defined that section in 'configSections'.


<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
   <configSections>  
    <section name="ApplicationSettings" type="System.Configuration.NameValueSectionHandler"/>      
  </configSections>  
    
  <ApplicationSettings>  
    <add key="ApplicationName" value="First Project"/>  
    <add key="Browser" value="Chrome"/>  
    <add key="SecretKey" value="XXXXX"/>  
  </ApplicationSettings>  
  <startup>  
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  </startup>    
</configuration> 

In this method, I have used GetSection() function for read values from sections.
I have created below function for reading value.


public static void ReadConfigurationUsingSection()  
    {  
        var applicationSettings = ConfigurationManager.GetSection("ApplicationSettings") as NameValueCollection;  
        if (applicationSettings.Count == 0)  
        {  
                Console.WriteLine("Application Settings are not defined. Pelase defined first.");  
        }  
        else  
        {  
            foreach (var key in applicationSettings.AllKeys)  
            {  
                Console.WriteLine(key + " = " + applicationSettings[key]);  
            }   
        } 

 String ApplicationName = applicationSettings["ApplicationName"];
 String Browser = applicationSettings["Browser"];
 String SecretKey = applicationSettings["SecretKey"]; 
    } 

In above function, we read all sections values in one variable using GetSection() function and then we read value one by one using 'Key'.

Third Method:

Suppose we have below 'app.config' file in project. We have one main section 'BlogGroup'. There is sub section 'PostSetting' in 'BlogGroup' section.


<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <configSections>     
    <sectionGroup name="BlogGroup">  
      <section name="PostSetting" type="System.Configuration.NameValueSectionHandler"/>  
    </sectionGroup>      
  </configSections>  
  
  <BlogGroup>  
    <PostSetting>  
      <add key="PostName" value="Getting Started With Config Section in .Net"/>  
      <add key="Category" value="C#"></add>  
      <add key="Author" value="Sameer"></add>  
      <add key="PostedDate" value="20 March 2018"></add>  
    </PostSetting>  
  </BlogGroup>          
    
  <startup>  
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>  
  </startup>  
</configuration>   


In this method, I have used GetSection() function for read values from sections.
I have created below function for reading value.


public static void GetConfigurationUsingSectionGroup()  
{  
    var PostSetting = ConfigurationManager.GetSection("BlogGroup/PostSetting") as NameValueCollection;  
    if (PostSetting.Count == 0)  
    {  
        Console.WriteLine("Post Settings are not defined. Please define first.");  
    }  
    else  
    {  
        foreach (var key in PostSetting.AllKeys)  
        {  
            Console.WriteLine(key + " = " + PostSetting[key]);  
        }  
    }
 String PostName = PostSetting["PostName"];
 String Category = PostSetting["Category"];
 String Author = PostSetting["Author"];
 String PostedDate = PostSetting["PostedDate"];
 
}  

In above function, we read all sub sections values in one variable using GetSection() function and then we read value one by one using 'Key'.
Please add comment if you have any question.

Friday 16 March 2018

How to Set Capabilities and Proxy Setting for Webdriver

Sometime we have to set some property of browser when initial driver instance. There is many properties like set download folder, PDF preview, 'SaveToDisk' option when download anything etc.
So, using DesiredCapabilities we can easily set properties of browser as per our requirement.

If you are suing proxy for Internet then you have to set proxy setting also with capabilities like auto detect setting, proxy type, HTTP proxy etc.

First, you have to add below packages into your code.

import net.lightbody.bmp.proxy.ProxyServer;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

We have to use DesiredCapabilities class object for set all required properties of browser.

 DesiredCapabilities capability = DesiredCapabilities.firefox();
 capability.setBrowserName("firefox");
   
 // Start proxy setting
 Proxy proxy = new Proxy();
 proxy .setAutodetect(false);
 proxy .setProxyType(ProxyType.MANUAL);
 proxy .setHttpProxy("localhost:8080");
 proxy .setSslProxy("localhost:8080");
 capability.setCapability(CapabilityType.PROXY, proxy);
 // Proxy setting end
   
 // start browser property setting
 FirefoxProfile Profile = new FirefoxProfile();
   
 Profile.setPreference("browser.download.manager.showWhenStarting", false);
 Profile.setPreference("browser.download.dir", "c:\\mydownloads");
 Profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
   "application/pdf,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/ms-excel");
 Profile.setPreference("browser.helperApps.alwaysAsk.force", false);
 // Disables PDF preview
 Profile.setPreference("pdfjs.disabled", true);   

 // End browser property setting
      
 capability.setCapability(FirefoxDriver.PROFILE, Profile);  // Add all properties to DesiredCapabilities object

 WebDriver driver = new FirefoxDriver(capability);  // Initiate webdriver instance with DesiredCapabilities object

Code Explanation :

Proxy proxy = new Proxy(); - Proxy class is used for setup proxy setting.

proxy .setAutodetect(false); - It is used for Disabled auto detect setting.

proxy .setProxyType(ProxyType.MANUAL); - It is used for set proxy type.

proxy .setHttpProxy("localhost:8080");
proxy .setSslProxy("localhost:8080");
Both commands are used for set HTTP and SSL proxy.

capability.setCapability(CapabilityType.PROXY, proxy);
At last once all proxy setting set then we have to add that proxy setting into capabilities.

FirefoxProfile Profile = new FirefoxProfile(); - For setting Firefox driver profile.   

Profile.setPreference("browser.download.manager.showWhenStarting", false);
It is for stop see download manager when download start

Profile.setPreference("browser.download.dir", "c:\\mydownloads");
It is for set download directory

Profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
 "application/pdf,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
          application/ms-excel");
It is for set 'SaveToDisk' option off when download start

Profile.setPreference("browser.helperApps.alwaysAsk.force", false);
It is for avoid popup for downloading file

Profile.setPreference("pdfjs.disabled", true);
It is for set PDF preview off 

capability.setCapability(FirefoxDriver.PROFILE, Profile);
It is for add all properties in to capability.

WebDriver driver = new FirefoxDriver(capability);
It is for initiate web driver instance with capability.


Please add comment if you have any question.

Wednesday 14 March 2018

How to Check Element Present on Page With Selenium Wrapper Automation

When you are are performing any operation on UI element then first you have to check weather element is present on page or not. If element is not present on page then your code will throw exception.

So, every time you have to check first weather element is present or not. If element is present then go ahead otherwise don't go ahead.

If you use isDisplayed() function for checking element then if element is not present then it will throw exception. So, you have to write that element operation in try/catch block. Same for all element operations. This is not good approach when you are working on selenium automation framework.

You have to use selenium wrapper automation for handling element check.

I have create below function for check element is present on page or not.


    public boolean mElementCheck(WebDriver driver, WebElement vElement)
    {
        final int WAIT_TIME = 2; //seconds
        final int RETRIES = 5;

        boolean bElementCheck = true;
                
        // The max wait time is 10 seconds(2 seconds with 5 retries)
        
        WebDriverWait wait = new WebDriverWait(driver, WAIT_TIME);
        int retries = 0;
        while (true)
        {
            try
            {
             wait.until(ExpectedConditions.visibilityOf(vElement));             
             bElementCheck = true;
             return bElementCheck;
            }
            catch (Exception e)
            {
             if (retries < RETRIES)
                {                 
                    retries++;
                    continue;
                }
                else
                {
                 System.out.println("WebElement not found.");                 
                 bElementCheck = false;
                 return bElementCheck;
                }
            }
        }
                        
    }

Function is returned Boolean value True/False. If element is present then True otherwise False.

I have used Explicit wait in function for handle wait while checking element present or not.

For more information regarding Wait handling in selenium then please go to below link.
Implicit Wait Vs. Explicit Wait Vs. Fluent Wait

Now, you can use this function easily with IF statement and it will not throw any exception if element is not present.

Please add comment is you have any question.

Tuesday 13 March 2018

Page Object Model (POM) Framework in Selenium

Why Page Object Model (POM) needed?

Page Object Model (POM) is one type of automation framework. When you are using selenium for automation then you come across scenario that many page objects (UI Element) are used in many test cases. You have to declare all that page objects for all the test cases. It is not good approach for automation to duplicate those page objects. Lots of memory also occupy due to this page objects duplication. To over come this problem we need to use POM structure for automation framework.


What is POM?
  • POM is framework (design pattern) or you can say its framework to create Object Repository for page objects (UI Element).
  • We need to create one separate class for store page objects in POM framework.
  • This class contains all the page objects of particular page.
  • We can use that page objects through object of that class.

Advantages

  • Page object repository is independent from actual code. So, we can reuse that repository in other project also.
  • Code flow and UI element identification is separate and due to that code will become more readable.
  • Code becomes less and more optimized.
  • We can easily integrate POM with JUnit/TestNG.

Implementation

As we discussed that in POM, we have to create separate class for page object repository.

Let's take an example of login page. In General, Login Page contains below three UI Elements.
  1. Username
  2. Password
  3. Login Button
First you have to create one package called 'PageObjects' then create one class called 'Login_Page' under that package.

Now, you have to add all three page objects of Login page into that class.

Your Login_Page class look like below.

package PageObjects;

import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

public class Login_Page 
{
 
 public Login_Page(WebDriver driver)
 {
  PageFactory.initElements(driver, this);
 }

 // list of all Login page objects
 
 @FindBy(id="Username")
 public WebElement Username;
 
 @FindBy(id="Password")
 public WebElement Password;
 
 @FindBy(xpath = "//input[@id='Loginbtn']")
 public WebElement Login;

}

You can see one constructor is there in above class. I have used below method in constructor.

PageFactory.initElements(driver, this);

This is used for initialize all page objects when we create object of this class.

Now, you can use all three page objects into your Login test case through 
Object of Login_Page class.

Note : You have to import PageObjects package into your class of Login test case.

public class Login_Test 
{
 
 public void Login()
 {
  WebDriver driver = new FirefoxDriver();
  
  driver.get("URL of Login Page");
  
  Login_Page objLogin_Page = new Login_Page(driver);
  
  objLogin_Page.Password.sendKeys("Username");
  
  objLogin_Page.Password.sendKeys("Passsword");
  
  objLogin_Page.Login.click();
  
 }

}

Here, you can see i have used all three page objects of Login_Page class through object of that class.

Same way we can use objects of other classes of PageObjects package into our framework.

Please add comment of you have any questions.

Monday 12 March 2018

How to Drag and Drop Element in Selenium

Sometime in testing, we need to do some operations with mouse and keyboard. 
Selenium web driver directly can not handle mouse and keyboard event like double click, right click, pressing key combination in keyboard.

We can handle such type of event with Actions class in selenium webdriver. We have to create object of that class and perform action which we want.

In this article, we will understand how to do drag and drop any element using selenium.

We have to use Actions class for drag and drop any element form one place to another place.There are two methods for drag and drop element in Actions class.

Method 1:

action.dragAndDrop(source, target);

Method 2:

action.dragAndDropBy(source, xOffset, yOffset);

Here, action is object of Actions class.

In first method, you have to pass two web elements. One is source element and second is target element at where you want to drop your source element.

In Second method, You have to pass only source web element. For target element you have to pass value of X coordinate and Y coordinate of target element. Value of  X coordinate and Y coordinate are Integer value.

Please add comment if you have any question.



Friday 9 March 2018

Chrome browser maximize issue in Selenium C#

If you are using C# in selenium and chrome browser then you will face issue for maximize browser.

If you are using maximize() function then it will throw exception. If you use capability for chrome browser for maximize it then it will also not work.

You have to use AutoIT for maximize browser. It is very easy to use.

Configuration:

First of all you have to add Nuget Package 'AutoItX' into your project. Please see below screen shot.




Once you are installed AutoItX into your project then you have to add 'AutoItX3Lib.dll' into references.

You can find that .dll file from where AutoItX is installed.



One more thing and very important is you have to register that .dll first because without register that .dll you can not use.

You can register  .dll file using 'regsvr32' command from command prompt.

regsvr32 path of .dll file

Now you all set for used of AutoIt functions.You have to use AutoItX3 class for access all functionality.

I have created below function for maximize chrome browser.


public void MaximizeBrowserWindow(IWebDriver driver, String vWindowName)
        {
            try
            {
                AutoItX3 autoIT = new AutoItX3();  // Create object of AutoItX3 class

                autoIT.WinSetState(vWindowName, "", autoIT.SW_MAXIMIZE); // For Maximize browser
                
                Console.WriteLine("Browser is maximized");
            }
            catch (NoSuchWindowException E)
            {
                Console.WriteLine(E.Message);
                Console.WriteLine("Browser is not maximized");                
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message);
                Console.WriteLine("Browser is not maximized");                
            }
        }

Code Explanation:


autoIT.WinSetState(vWindowName, "", autoIT.SW_MAXIMIZE);

vWindowName : It is Browser window name.
autoIT.SW_MAXIMIZE : It is for maximize browser.

Please add comment if you have any question.

Popular