Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Showing posts with label Selenium Automation. Show all posts
Showing posts with label Selenium Automation. Show all posts

How to extract CSS properties of an element: Interview question Selenium

During functional test script creation using selenium , we came across steps like verify the background color , font size or the text color of the element. These are the different CSS properties associated with an element. We can extract the value of CSS properties using the below code:

What we require is to:
  • Identify the element 
  • Get CSS Attribute on the element
  • Store the property in a variable

WebElem = driver.findElement(By.id("testbhd"));

// to get background color
String bgColor = WebElem.getCssValue("background-color");

// to get text color
String bgColor = WebElem.getCssValue("color");

// to get font size
String bgColor = WebElem.getCssValue("font-size");

Continuing TestNG test execution post assertion failure

Assertions are used to validate if a condition holds true. In previous article, we discuss on how to create assertion in TestNG.


See: How to work with Assertions in TestNG tests.


Assertion added in previous article were hard assertion, i.e : current test execution stops once an assertion fails and the next test in the test suite is executed while using hard assertions. When we use import org.testng.Assert library, the test execution stops once an error is encountered. This is useful to stop an test execution in case of critical defect in the test, and move to next test in the suite.


Example of creating multiple test in explained in the below TestNG.xml


 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <test name="Test1">  
 <classes>  
   <class name="testNG.assertionVal"/>  
 </classes>  
 </test>  
 <test name="Test2">  
 <classes>  
   <class name="testNG.NewTest1"/>  
 </classes>  
 </test>  
 </suite>  

There can be scenario where we do not want to stop test execution due to a minor validation defect.  In that scenario we can use the concept of soft assertion, i.e the test case execution will continue although the test will be marked as failed in the final results but will be executed until the test flow is completed or an hard assertion failure condition occurs.


Below points are important to note from current article:

  • There are two types of assertion Hard assertion and soft assertion.
  • Hard assertion use import org.testng.Assert library
  • Soft assertion use import org.testng.asserts.SoftAssert library
  • Step  softas.assertAll() needs to be added to display the validation failure from soft assertion failure


Below code explains how to use soft assertion in the test.


 package testNG;  
 import org.testng.Assert;  
 import org.testng.annotations.Test;  
 //soft assertion will use the below softAssert class  
 import org.testng.asserts.SoftAssert;  
 public class assertionVal {  
      // Create an soft assertion object softas   
      SoftAssert softas = new SoftAssert();  
      @Test  
      public void assertVal()   
      {  
           //Create an assertion similar to hard assertion as shown below   
           softas.assertEquals("aaaa", "bb");  
           softas.assertEquals("aa","aaccc","asserts exists");  
           // this is an example of hard assertion, test will stop execution   
           //at this step in case error is encountered.  
           Assert.assertEquals("aa", "aa");  
           System.out.println("nitin");  
           //This step is very important as without this step,  
           //no soft assertion failure will be reported in test result.  
           softas.assertAll();  
      }  
 }  

How to work with Assertions in TestNG tests

     Assertions are added in TestNG to validate whether a condition is true or false and report in test results the execution state of condition. For example in selenium test for login, we provide valid username and password and login, we expect the title to be displayed correctly in the page. Assertions are used in code, where we need to validate the state of an object properties and fail the test in case expected conditions are not met.


Different type of assertions:


  • Assert.AssertEquals(Expected condition, Actual condition) – This compares the expected condition with actual condition and fails the test in case the assertion fails.Different object types can be compared using Assert.AssertEquals
 
  • Assert.AssetEquals(Expected condition, Actual condition, Message)- This compares the expected condition with actual condition and fails the test in case the assertion fails displaying the message as defined while calling the assertion.
 
  • Assert.assertFalse(Boolean condition) - Asserts that a condition is false
 
  • Assert.assertFalse(Boolean condition, String Message )- Asserts that a condition is false. If it isn't, an Assertion Error, with the given message, is thrown.

  • Assert.assertTrue(Boolean condition, String Message )- Asserts that a condition is true. Assertion fails if condition is not true and string message is displayed.

  • Assert.AssertNull(object) – Validates if a assertion is null.


There are various other assertion which we can add in TestNG test. The issue with assertion is case execution stops in case an assertion fails. So if we do not want to stop a test on failure and continue with test execution, using assert statement will not work, instead we can wrap the assert function to verify the test condition and continue with test execution. We will discuss in future article for how to use soft assertion in the test scripts.


Below code explains how to use different assert in TestNG tests.


 package testNG;  
 import java.io.File;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 import org.testng.Assert;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.Test;  
 public class assertionVal {  
      WebDriver driver;  
      @BeforeTest  
      public void setup()   
      {  
           File file = new File("D:\\selenium\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           driver = new InternetExplorerDriver();  
      }  
      @Test  
      public void assertVal()   
      {  
           driver.navigate().to("http://qaautomationqtp.blogspot.com");  
           Assert.assertEquals("Learning Automation Concepts in QTP", driver.getTitle());  
           //Assert to compare two values and reporting a message in case validation fails  
           Assert.assertEquals("aaa", "aaa", "this is the first test and value does not match");  
           //Assert to validate a boolean condition as false   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
           //Assert to validate a boolean condition as true   
           Assert.assertFalse(driver.getTitle().contentEquals("Learning Automation Concepts in QTP"));  
        //Assertion to validate an object is not null.  
        Assert.assertNotNull("driver");  
      }  
 }  

Working with TestNG.XML to execute Selenium test suite

While using TestNG, we can execute multiple tests or methods in the project based on the test annotations, the methods, and classes in the Project. We will execute the test suite from eclipse using TestNG.xml in this article to keep it simple, although we can execute the Test Suite from command line or through Ant.

Pre-condition:

Focus of this article:

  • How to create TestNG xml file to run test suite.
  • How to run test from the TestNG xml file in eclipse.


Let us consider the below two classes in a Java Project. To Keep it simple, we are just outputting a value in each of the Test method. Suppose we have two different classes, we can create a test suite using testng.xml file and run the test suite from eclipse as shown in the below image.


Creating TestNG.xml file for different scenarios:


A. Run all the tests in both classes NewTest and NewTest1. This will execute all the methods with beforetest annotation in both the classes, followed by methods with test annotation, and then methods with afterText annotation.

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
  <test name="Test">  
   <classes>  
    <class name="testNG.NewTest"/>  
       <class name="testNG.NewTest1"/>  
   </classes>  
  </test>  
 </suite>  


B. Run test in class NewTest and then the methods in NewTest1 class:

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
  <test name="Test1">  
   <classes>  
    <class name="testNG.NewTest"/>  
         </classes>  
  </test>  
  <test name="Test2">  
   <classes>  
    <class name="testNG.NewTest1"/>  
   </classes>  
  </test>  
 </suite>  

C. Executing all tests in a package with name as TestNG(Note: TestNG is the name of package in our example, it can be any name other than TestNG also)

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <test name="Test1">  
   <packages>  
    <package name="testNG" />  
   </packages>  
  </test>  
 </suite>  

D. Executing all tests based on the group Name:

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <test name="Test1">  
  <groups>  
   <run>  
    <include name="testemail"/>  
    <exclude name="testnoemail"/>  
   </run>  
  </groups>  
   <classes>  
    <class name="testNG.NewTest"/>  
    <class name="testNG.NewTest1"/>  
   </classes>  
 </test>  
 </suite>  

E. Executing specific methods by including methods in the class:

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">  
 <suite name="Suite1">  
 <test name="Test1">  
 <classes>  
   <class name="testNG.NewTest">  
    <methods>  
     <include name="emailval" />  
    </methods>  
   </class>  
   <class name="testNG.NewTest1"/>  
 </classes>  
 </test>  
 </suite>  

What are Annotations in TestNG: Selenium Automation


In the Previous tutorials, we explained how to add TestNG to eclipse and how to set up for creating the first test using TestNG. In this article, we will understand what annotations in TestNG are and how they are used:


When we create a test in TestNG, we divide the code into different annotations based on which section needs to be executed and in which order. 

Let us take an example, We have three different tests to be automated. Each of the test starts with Login into application, In the next step, the user has either to view e-mails, write e-mail or verify successful login only. In the final step, we have to log out of application.


To code this, we have to login into application in each of the three test, so we can define this method or code in @BeforeTest.
Next we will define all the tests to be executed with annotation @Test and can assign group of test to be executed using group with test.

Once the test is executed, user will log out from application, this we will tag with annotation @AfterTest.

Below code explains how the three annotations can be used in the test. There are many more annotations which we can add in the test to give logical structure to the test.

 package testNG;  
 import org.testng.annotations.Test;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.AfterTest;  
 public class NewTest {  
  @BeforeTest  
  public void Login()  
  {  
       System.out.println("Login into application");  
  }  
  @Test(groups = { "testemail" })  
  public void mailval()  
  {  
       System.out.println("test e-mail");  
  }  
  @Test(groups = { "testemail" })  
  public void emailval()   
  {  
       System.out.println("e-mailvalidated");  
  }  
  @AfterTest  
  public void Logout()  
  {  
       System.out.println("Logout from application");  
  }  
 } 

                                  Annotations in TestNG

   Below table explains the different annotation used in TestNG:


Annotation
Description
@BeforeSuite
Annotated method to be executed before all tests in the suite have run. 
@AfterSuite
Annotated method to be executed after all tests in the suite has run. 
@BeforeTest
Annotated method to be executed before any test method belonging to the classes inside the <test> tag is run. 
@AfterTest
Annotated method to be executed after all the test methods belonging to the classes inside the <test> tag have run. 
@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. 
@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. 
@BeforeClass
The annotated method to be executed before the first test method in the current class is invoked. 
@AfterClass
The annotated methods to be executed after all the test methods in the current class have been run. 
@BeforeMethod
The annotated method to be executed before each test method. 
@AfterMethod
The annotated method to be executed after each test method.

In the next article, we will explain how a test suite is defined in TestNG and how does a test pass or fail in TestNG i.e how to add assertions in TestNG.

Creating first TestNG test using eclipse for Selenium WebDriver


TestNG provides a testing framework to test the application. TestNG framework can be used to write unit test, integration as well as functional tests. Our objective in this blog will be to understand and implement TestNG framework while automating with Selenium WebDriver using eclipse.


In the previous article, we explained how to install TestNG libraries with eclipse. In this article, we will explain how to create first TestNG test in eclipse.

Pre-Requisite: We have installed TestNG as discussed in previous article.


Steps to create first TestNG test in eclipse:

  • Create a new Project in eclipse as shown in the image below and add the TestNG library:

Add TestNG library to eclipse java Project



Add TestNG library
Add caption

  • Once we have added the library, we can use the library in our test.

Creating a testNG Class in the java Project:


A testNG test is executed based on the testNG annotations in the TestNG class.

Creating a testNG class
New TestNG class

Below code will be generated once we click on finish.


 package testNG;  
 import org.testng.annotations.Test;  
 import org.testng.annotations.BeforeTest;  
 import org.testng.annotations.AfterTest;  
 public class NewTest {  
  @Test  
  public void f() {  
  }  
  @BeforeTest  
  public void beforeTest() {  
  }  
  @AfterTest  
  public void afterTest() {  
  }  
 }  

Setting Up TestNG with eclipse


The below image explains how to setup TestNG with eclipse.


A. Navigate to Help>Install new Software.

B. Search for TestNG or http://beust.com/eclipse in Step B.)

C. In Step C.), Select checkbox for TESTNG and click on next.

D. In step D.) accept  the license agreement.

E. Software download will start and will be installed.

F. Once download is completed, it will ask to restart the eclipse. Click on Yes. This will restart eclipse.



Installing TestNG

In the next article, we will discuss how to create a TestNG test for selenium in eclipse.

Code to Capture screenshot in Selenium WebDriver Automation

When we run a script in any automation framework, Capturing and reporting images especially in case of failure is required. In this article, we will discuss different ways to capture screenshot and how to report with screenshot.


Steps to reporting with screenshot:


  • Create an independent function to capture screenshot.
  • Call the screenshot function from the reporting function based on whether to capture screenshot or not.

Different ways to capture screenshot are:


  • Using Java.awt class - Recommend to use if automation interacts with other application together with web application.

  • Using Selenium webdriver (selenium.TakesScreenshot) - Use this to capture screenshot if only web application is to be tested which are identified using selenium webdriver.

Below code shows how to capture screenshot using the above classes:

1:  package testproject;  
2:  import java.awt.Rectangle;  
3:  import java.awt.Robot;  
4:  import java.awt.Toolkit;  
5:  import java.awt.image.BufferedImage;  
6:  import java.io.File;  
7:  import java.util.List;  
8:  import javax.imageio.ImageIO;  
9:  import org.apache.commons.io.FileUtils;  
10:  import org.openqa.selenium.OutputType;  
11:  import org.openqa.selenium.TakesScreenshot;  
12:  import org.openqa.selenium.WebDriver;  
13:  import org.openqa.selenium.ie.InternetExplorerDriver;  
14:  public class testingC {  
15:       static WebDriver driver;  
16:       public static void main(String[] args) throws InterruptedException {  
17:            // Connect to the Internet driver server and create an instance of Internet explorer driver.       
18:            File file = new File("D:\\selenium\\IEDriverServer.exe");  
19:            System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
20:            try  
21:       {  
22:                 driver = new InternetExplorerDriver();  
23:            }  
24:            catch(Exception e)  
25:            {  
26:                 driver=new InternetExplorerDriver();  
27:            }  
28:            driver.navigate().to("https://qaautomationqtp.blogspot.com");  
29:            try {  
30:                 Capturescreenshot("testingscr.png");  
31:                 CapturescreenshotJava("D://testingscr1.png");  
32:            } catch (Exception e)   
33:            {  
34:                 e.printStackTrace();  
35:            }  
36:       }  
37:          public static void Capturescreenshot(String StrscreenshotName) throws Exception   
38:          {  
39:              File generateFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
40:              String strOutFile = "D:\\"+StrscreenshotName;  
41:              FileUtils.copyFile(generateFile, new File(strOutFile));  
42:          }  
43:          public static void CapturescreenshotJava(String StrscreenshotName) throws Exception   
44:          {  
45:                    Robot robot = new Robot();  
46:                    Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());  
47:                    BufferedImage scrImg = robot.createScreenCapture(screenRect);  
48:                    ImageIO.write(scrImg, "png", new File(StrscreenshotName));  
49:              }   
50:  }  

Using ExpectedConditions for explicit wait in Selenium Webdriver.

In this article, we will discuss on different explicit wait asking the test script to wait for some time based on the expectedcondition for object defined by locator.Before discussing further, let us have a look at generic syntax for adding an explicit wait in the test using expected condition.


WebDriverWait wait = new WebDriverWait(driver, 1000);

wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("QAmail"))); 


In the first statement, we create an instance wait of the WebdriverWait object with arguments as driver object and the time to wait for existence of element.


In the next statement, we are asking the script to wait until the expected condition is met. In the above script, test script will wait for max 1000 second for element identified with linkText as "QAmail" to be available in the DOM for the page.


Let us define what are the different ways to use expected condition based on which we can add explicit wait in the object.

a. presenceOfElementLocated - Verify presence of element in the DOM.

WebDriverWait wait = new WebDriverWait(driver, 1000);

wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("QAmail"))); 


b. Using elementToBeClickable

wait.until(ExpectedConditions.elementToBeClickable(By.linkText("TGmail")));


c. Using invisibilityOfElementLocated

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.linkText("tGmail")));

 

d. invisibilityOfElementWithText - Validating the invisibility of element with text for the element provided.

wait.until(ExpectedConditions.invisibilityOfElementWithText(By.xpath("//div[@id='_eE']"), "tGmail")); 


e. textToBePresentInElement - Validating the text to be present in the element defined by locator.

wait.until(ExpectedConditions.textToBePresentInElement(By.xpath("//div[@id='_eE']"),"Gmail")); 


f. visibilityOfElementLocated by locator.

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='_eE']"))); 


g. titleContains - Wait until the title is displayed correctly

wait.until(ExpectedConditions.titleContains("QA Automation QTP"));


h. alertIsPresent - waits for alert to appear in the window.

wait.until(ExpectedConditions.alertIsPresent());

How to get attributes values of element in Selenium using getAttribute Method

Using getAttribute, we can extract the value of attribute of an element in Selenium WebDriver. Extracting values of attribute of element can be helpful in a number of ways. Some of the important use of getattribute method are as follows: 


  • Name of all the links or button or an object type in the Page.
  • Validating if object with particular property exists in the Page.
  • Extracting the href value for a button/link.
  • Extracting values of element of a particular class or Id. For e.g: If error message are displayed on the page with the same class. We can get all the error messages displayed getting text attribute for all element with the common class name.

Below code explains use of getattribute in Selenium Webdriver for the above purpose.

 package testproject;  
 import java.io.File;  
 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class testingC {  
      static WebDriver driver;  
      public static void main(String[] args) throws InterruptedException {  
           // Connect to the Internet driver server and create an instance of Internet explorer driver.       
           File file = new File("D:\\selenium\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           try{  
                driver = new InternetExplorerDriver();  
       driver.manage().window().maximize();  
           }  
           catch(Exception e)  
           {  
                driver=new InternetExplorerDriver();  
           }  
           driver.navigate().to("https://google.com");  
           //function to get names of all the links in the Page  
           getALLNameforObject("link");  
           // function to validate a particular object with particular text appears in the Page  
           ValidateObjectExists("link", "About");       
           //   
      }  
      public static void getALLNameforObject(String strObject)  
       {  
           if(strObject.toLowerCase().trim().contentEquals("link"))  
           {  
                strObject = "a";  
           }  
           if(strObject.toLowerCase().trim().contentEquals("button"))  
           {  
                strObject = "button";  
           }  
           List<WebElement> elemLink = driver.findElements(By.tagName(strObject));  
           int intLinksinPage = elemLink.size();  
           System.out.println(intLinksinPage);  
           for (int i = 0;i<intLinksinPage;i++)  
           {  
                System.out.println("The name of the link " + (i+1) +" in the page is :- " + elemLink.get(i).getAttribute("text"));  
           }  
      }  
      public static void ValidateObjectExists(String strObject, String ObjName)  
       {  
           if(strObject.toLowerCase().trim().contentEquals("link"))  
           {  
                strObject = "a";  
           }  
           if(strObject.toLowerCase().trim().contentEquals("button"))  
           {  
                strObject = "button";  
           }  
           List<WebElement> elemLink = driver.findElements(By.tagName(strObject));  
           int intLinksinPage = elemLink.size();  
           System.out.println(intLinksinPage);  
           for (int i = 0;i<intLinksinPage;i++)  
           {  
                if(elemLink.get(i).getAttribute("text").contentEquals(ObjName))  
                {  
                     System.out.println("Link exists in Page with text " + elemLink.get(i).getAttribute("text"));  
                }  
           }  
      }  
 }  

Highlighting an element using JavaScriptexecutor: Selenium Code Solution


Problem Statement: How to highlight an element in Selenium Webdriver?


Solution : We can highlight an element in Selenium WebDriver by creating a custom method to highlight an element using JavaScriptexecutor.


What is JavaScriptexecutor?


JavaScriptexecutor class provides mechanism to execute Javascript through selenium driver. JavaScript executor provides two methods to execute javascript in the code:


a.) executeAsyncScript - Execute an asynchronous code of JavaScript
b.) executeScript - Executes a code of JavaScript.


Parameters for the two methods are the Script to be executed and arguments for the script.


Below package needs to be imported to use JavascriptExecutor:


import org.openqa.selenium.JavascriptExecutor;


Below code explains how to use JavaScriptExecutor to highlight an element in Selenium WebDriver using Java.


 import java.io.File;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class testingC {  
      static WebDriver driver;  
      public static void main(String[] args) throws InterruptedException {  
           // Connect to the Internet driver server and create an instance of Internet explorer driver.       
           File file = new File("D:\\selenium\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           try{  
                driver = new InternetExplorerDriver();  
                //added new line to maximise browser on launch  
       driver.manage().window().maximize();  
           }  
           catch(Exception e)  
           {  
                driver=new InternetExplorerDriver();  
           }  
           //Navigate to the webpage and identify the element to be highigted  
           driver.navigate().to("https://qaautomationqtp.blogspot.com");  
           WebElement element = driver.findElement(By.linkText("Play"));  
           //highlight the element  
            methodhighlightElement(element);  
         element.click();            
      }  
      public static void methodhighlightElement(WebElement element) throws InterruptedException   
       {  
         JavascriptExecutor js = (JavascriptExecutor) driver;  
         js.executeScript("arguments[0].setAttribute('style','border: solid 8px blue')", element);   
         Thread.sleep(2000);  
         js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");  
      }  
 }  

How to Create and execute Runnable JAR file for Java Project from command Prompt/Batch file

In this article, we will discuss steps to create an executable JAR file from a java project. This can be useful for our selenium Project. We are using Eclipse IDE for illustrating the example.


Prerequisite – It is assumed a java project is created.


Steps to create an executable jar file:


 Define the Run Configuration for execution

1.       Navigate to Run>Run Configuration for the Project.

2.       Select Java Application  and click on New launch configuration

3.       Provide the name to configuration and provide the main lass name to run.

4.       You can also define default argument for the execution.

5.       Save the configuration


Creating run configuration
Creating run configuration

 

Export the Project as executable Jar file


1.       Click on Project>Export

2.       Select export destination as Java>Runnable JAR files


Exporting as runnable JAR file
Exporting as runnable JAR file

3.       Select Run Configuration as one defined in step A.


Providing export location and launch configuration
Providing export location and launch configuration

4.       Provide export destination

5.       Click on finish


Run the executable JAR file 


 Through command prompt.


1.       Open command prompt

2.       Navigate to folder in which JAR file is saved.

3.       Run the following command  java -jar driverJAR.jar where driverJAR.jar is the name of JAR file



Double clicking on a batch file 


1.       Create a new text file in the same location as the JAR file.

2.       Rename the file as test.bat, thus creating a batch file.

3.       Add following content in the bat file

@echo "this is for testing the jar file"

java -jar testingJAR.jar

pause


4.       Save the file.

5.       Double click the file, it will run the jar file 



Selenium - Waiting using implicit, explicit and fluent classes for Objects

While automating with Selenium, we may require to pause the execution for specific duration or until a specific condition is satisfied. In this article, we will discuss on common scenario where we might like script to wait for few seconds or minutes. Before going to discuss different methods to wait in selenium Web driver, 

Let us discuss on scenarios where we require to pause the execution.
  • In case, we require to execute some other process between execution in the web browser. E.g. compressing some files to be uploaded from web.
  • In case of Page load, waiting until the new pages opens.
  • In case of availability or value displayed in controls, enable/disable of object in the Page or specific conditions is satisfied. 

Below are the different wait method used with selenium scripts for synchronization:

  •  Using Thread.sleep

  Thread. Sleep (10000) will make the script pause for 10 sec. Thread.sleep is used in script in case of execution outside of selenium code. For e.g.: Suppose in between performing browser operation, we need to execute some exe file which takes some time for execution to complete.

  • Using Implicit Wait 

 Implicit wait tells Webdriver to poll the DOM for a certain amount of time for object Identification and wait for availability of object, if not available at the instance of step execution. Once set, the implicit wait is set until the webdriver instance is closed.If the object is found below 50 sec , it will move to next step in the script.
          WebDriver driver = new  InternetExplorerDriver();
         driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

  • Using Fluent Wait 

 Another wait which is very similar to Explicit Wait is fluentWait.
           FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
         //define the timeout – this is time the driver will wait for condition to be              satisfied.
        wait.withTimeout(10000, TimeUnit.MILLISECONDS);
        // define the poll time, here it will poll the DOM after 200 ms and will poll at fixed  interval until 10000 ms
       wait.pollingEvery(200, TimeUnit.MILLISECONDS);
       driver.get(url);
      // we define the wait time for a specific condition to be satisfied using                              wait.until(ExpectedConditions.condition) as explained below where the driver will wait until    the title of the Page contains “qaautomationqtp.blogspot.in”; We can also select from multiple conditions as shown in screenshot below:
 wait.until(ExpectedConditions.titleContains("qaautomationqtp.blogspot.in"));
 //We can also define to ignore specific types of exceptions using wait.ignoring (exception.class)e.g. :
  wait.ignoring(NoSuchElementException.class);


  • Using Explicit Wait   

WebdriverWait is an extension of fluent class but has functionality compared to fluent class for waiting for an object including pooling time, ignore settings to name a few.
         WebDriverWait wait = new WebDriverWait(driver, 50)
         wait.until(ExpectedConditions.elementToBeClickable(By.Id("dra_reference")));

WebdriverWait and fluent class can be considered as example of explicit wait as are defined explicitly for an element in the page, e.g. in wait.until(ExpectedConditions.elementToBeClickable(By.Id("dra_reference")));

It is explicitly waiting for the condition specific to object with Id as "dra_reference" to be clickable.
Implicit wait is not defined for specific object but checks for the existence of each element used and are implied until the driver instance is closed.

So if an object is not getting loaded before the script fails, give the object some time to load and let the script wait for object to get identified. If all the objects are slow, give an implicit wait for the driver that will wait for all the objects to be available or an explicit wait, waiting explicit for an objects condition. Hope this make some sense.