DYNAMIC BINDING AND UPCASTING IN SELENIUM


Dynamic Binding / Upcasting in selenium


Dynamic Binding


    • Dynamic Binding means object type can be determined at run time only 
    • The dynamic binding can be achieve by method overriding. JVM decides which method should be called for a particular call at runtime i.e. the method remains unknown until runtime.
    • Suppose, there are two classes and all override the same method which belongs to their parent class and an another class having main method
    • In Below program calling on run method depends on the type of object reference variable, i.e as per the below example calling of run method will give output as "RemoteWebDriver is running..." even though the object is created for ChromeDriver.


       class RemoteWebDriver

      {  

      void run()

                {
                System.out.println("RemoteWebDriver is running...");
                }  
     }  
      
      class ChromeDriver extends RemoteWebDriver
     {  
      void run()
                 {
                  System.out.println("ChromeDriver is running...");
                 }  
                     public static void main(String args[])
                  {  
                   RemoteWebDriver a=new ChromeDriver();  
                   a.run();  
                   }  
     }  


      • With the above example you must be curious why we are extending the ChromeDriver with RemoteWebDriver and interviewer can also asked these type of questions since as per the selenium Architecture ChromeDriver class extends the RemoteWebDriver then we upcast the browser classes to WebDriver instead of Parent class known as RemoteWebDriver


      Interview Questions 



      Question 1 :-  Why we generally upcast the browser related child class to WebDriver, and not RemoteWebDriver class (RemoteWebDriver being the super most class in SELENIUM)?

      Answers :-  We can upcast browser object to RemoteWebDriver, WebDriver,
      TakesScreenshot , JavascriptExecutor etc, but its a standard practice is to upcast to WebDriver interface. This is as per the SELENIUM coding standard set by the SELENIUM community.

      Question 2 :- Difference Between the WebDriver and RemoteWebDriver ?

      Answers :- If we are using Below line of code to start the browsers in selenium, then we are accessing the Chrome on our local machine directly which we generally do.

      Webdriver driver = new ChromeDriver();


      However if we use RemoteWebDriver instead of WebDriver as shown below, then it means we want to access and control the desired browsers in Node PC over the Grid using the Capability(settings) and Hostname or IP of the Selenium HUB running.

      Thus  If we want to use RemoteWebDriver, it requires us to tell it where the Selenium Server (Grid) is located and which webbrowser we want to use. example below:-


      WebDriver driver = new RemoteWebDriver(new URL("http://localhost:

      4444/wd/hub"), DesiredCapabilities.firefox());



      In above example assumes that Selenium Server is running on localhost with the default port of 4444. The nice thing about this is you can run Selenium Server on any machine, change the URL to point to the new machine and run the tests. 

      And one more difference, most of you guys already know that WebDriver is and interface and RemoteWebDriver is an class in selenium

      WebDriver driver = new ChromeDriver() || explain || Upcasting in Selenium




      WebDriver driver = new ChromeDriver()



      Upcasting / Dynamic Binding - in selenium



      • In the above statement WebDriver is an interface and ChromeDriver is an class.
      • Driver is the Refernce Variable of WebDriver interface.
      • New is the keyword used in Java to create an object of ChromeDriver().
      • ChromeDriver() is the constructor of ChromeDriver class which initialize the object, this is use to launch the Chrome Driver.
      • This is also known as Dynamic Binding in Java 

      List of Interfaces in Selenium



      Selenium - Interfaces


      Selenium Interface List




        • Below are the list of interfaces we have in selenium webdriver and all these interfaces has abstract and non- static methods.

            • SearchContext
            • WebDriver
            • TakesScreenshot
            • JavascriptExecutor
            • Navigation
            • OutputType
            • WebElement
            • TargetLocator
            • Alert
            • Action
            • ExpectedConditions
            • Options
            • Timeouts




          Selenium Architecture Java



            Selenium - Java Architecture (Interfaces & Classes)



            Selenium Architecture (Interfces and Classes) 



            • In the Previous blog we already discussed about the Selenium Webdriver Architecture (WebDriver Architecture) to understand how Selenium WebDriver works and interact with browsers.
            • In this blog we will be understanding how selenium classes and interface interact with each other and what is the parent class and inteface we have in selenium.

            Selenium WebDriver Architecture with Super class and Super Interface




            • SearchContext  is the super interface (Parent Inteface) present in SELENIUM WebDriver.
            • An interface called WebDriver extends SearchContext interface.
            • All the interfaces (Interface) defined in SELENIUM are implemented by a super class (Parent class) called RemoteWebDriver.
            • RemoteWebDriver is again extended by all the browser supported by selenium few example as:
                • FirefoxDriver 
                • ChromeDriver 
                • InternetExplorerDriver



            Relative Locators in Selenium (Selenium 4 Features)



            Relative Locators 

            • Till now we have used many locators like Xpath, Css, Id, Name, Link etc. in total so far we have 8 locators, however with selenium 4, we will be using few more locators.


            • Selenium 4 provide us a new way to find the WebElement or i would say (Near by WebElement) based on the other Element present in the DOM


            • Selenium 4 provide the functionality of "Relative Locators" This functionality is added to help us locate elements that are nearby other elements. The Available Relative Locators are:
              • above
              • below
              • toLeftOf
              • toRightOf
              • near

            Syntax 

            driver.findElement(withTagName("Element to find").below(By.xpath("Element present in DOM"))).sendKeys("Selenium");

            Explanation:-


            • FindElement method now accepts a new method "withTagName".
            • "withTagName" function accept the tag Name of a webElement which we are trying to find to perform further actions as sendKeys().
            • .below is the Relative Locator which internally use JavaScript function getBoundingClientRect() to find the relative elements.
            • Below Locator takes the input argument as a webElement.

            Sample Code 

            package Demo.Selenium4updates;
            import java.util.List;
            import org.openqa.selenium.By;
            import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.chrome.ChromeDriver;
            import org.openqa.selenium.interactions.Actions;
            import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
            import org.testng.annotations.Test;
            import io.github.bonigarcia.wdm.WebDriverManager;
            public class Selenium4RelativeXpath2rediff {
            public static WebDriver driver ;
            @Test
            public static void test() 
            {
            try {
            WebDriverManager.chromedriver().setup();
            driver= new ChromeDriver();
            driver.manage().window().maximize();
            driver.get("http://register.rediff.com/register/register.php?FormName=user_details");
            Thread.sleep(3000);
            driver.findElement(withTagName("input").below(By.xpath("//*[@id='tblcrtac']/tbody/tr[3]/td[3]/input"))).sendKeys("tgerst");
            }
            catch(Exception e )
            {
            e.printStackTrace();
            System.out.println("Getting error");
            }
            }

              • Using  above code we are sending inputs to Rediff ID,  Please have a look to below screen.




              Missing artifact com.sun:tools:jar:0



                "Missing artifact com.sun:tools:jar:0" In POM.XML 

                Error Detail
                Multiple annotations found at this line:
                - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://
                maven.apache.org/xs
                - Missing artifact com.sun:tools:jar:0



                There could be multiple reasons for this issue.

                1. Added Wrong MVN repository as mention below.(example below)

                <!-- https://mvnrepository.com/artifact/net.sourceforge.cobertura/cobertura -->
                <dependency>
                    <groupId>net.sourceforge.cobertura</groupId>
                    <artifactId>cobertura</artifactId>
                    <version>2.1.1</version>
                    <scope>test</scope>
                </dependency>

                2. Missing Tools: Jar :0 - (Change JRE to JDK )

                In Eclipse IDE go to Window / Preferences / Java / Installed JREs point to a JDK installation.

                Make sure you look into the folder C:/Program Files/Java/jdk1.8.0_version/lib instead of C:/Program Files (x86)/Java/jdk1.8.0_version/lib

                Unknown Jre Version of jre1.8.0_241





                • Some time we get below error message "Unknown Jre Version of jre1.8.0_241" while running our test cases in selenium 


                • Best way to resolve this problem is to Go to Properties of the project.
                • Select Java build path and Verify the presence of JRE library.
                • Now you will see some kind of red cross symbol there as below.

                • Now delete this Libraries and install JRE if not exist in your system or reload this library to your project again.
                • Now restart the Eclipse and you will be able to run your code.


                Note:- So the main reason for issue was, somehow your JRE got issues thus we just have to re- add the library again.

                Hope it resolved your issue, if no please let us know.. will try to help..

                Basic Terms used in selenium



                Basic Terms used in selenium

                • While working with selenium its always a good practice to understand the basic terms as well.
                • So i am trying to list down few of the important terms used in selenium and i hope you guys will help me by suggesting more terms to incorporate in this blog


                  • Client
                    • The machine on which we are running WebDriver API.



                  • Server

                    • The machine running the RemoteWebDriver, or any specific browser that implements the JSON wire protocol directly, such as the FirefoxDriver or ChromeDriver.



                    • Session

                      • The server should maintain one browser per session. Commands sent to a session will be directed to the corresponding browser.


                      • WebElement

                          • An object in the WebDriver API that represents a DOM element on the page. like button, Text box, Dropdown etc.

                      Explain Selenium WebDriver Architectue




                      Selenium WebDriver Architecture


                      How Selenium WebDriver Work





                      Selenium Architecture Explanation 

                      • Once we Trigger our test, complete selenium code (Client) written by us will be converted to JSON (RESTful web service ) format
                      • Next step is to sent the JSON to Browser Drivers through HTTP Protocol.
                      • Browser driver communicate with its respective browser and execute the commands by interpreting JSON .
                      • Browser Driver receives responses back from the browser and it sends JSON response back to client.

                      More Technical Aspect

                      • Any implementation of WebDriver that communicates with any of the browsers use a common wire protocol.
                      • This wire protocol defines a Restful web service using JSON over HTTP. 


                      What is WebDriver in selenium



                      What is Selenium WebDriver

                      • WebDriver is an interface present in the selenium which has lots of methods like findElement, findElements, get, getTitle etc..

                      • Parent interface of WebDriver is SarchContext.

                      • Its an open source Automation Testing Framework / set of libraries/ Collection of open source API,  primarily it is for Automating Web Applications.

                      • Selenium WebDriver is platform-independent since the same code can be used on different Operating Systems Selenium Webdriver is platform-independent since the same code can be used on different Operating Systems (Windows , Mac Linux)

                      • Go to https://selenium.dev/selenium/docs/api/java/index.html. On the left hand side menu, whatever you see in italic is an interface. Notice that WebDriver too is in italic & hence is an interface. Click WebDriver link, the below page should open






                      Features of selenium

                      • Multiple Browser
                      • Multiple Language
                      • Multiple OS 



                      java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V

                      Issue :- java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V

                      below Scripts to take a screen shot for a specific element from a page using selenium 4.5

                      package Demo.Selenium4updates;

                      import java.io.File;
                      import java.io.IOException;

                      import org.apache.commons.io.FileUtils;
                      import org.openqa.selenium.By;
                      import org.openqa.selenium.OutputType;
                      import org.openqa.selenium.WebDriver;
                      import org.openqa.selenium.WebElement;
                      import org.openqa.selenium.chrome.ChromeDriver;
                      import org.testng.annotations.Test;

                      import io.github.bonigarcia.wdm.WebDriverManager;

                      public class Selenium4features {

                      @Test
                      public static void test() throws IOException
                      {

                      WebDriverManager.chromedriver().setup();
                      WebDriver driver = new ChromeDriver();
                      driver.get("https://www.yet5.com/");
                      driver.manage().window().maximize();
                      WebElement element = driver.findElement(By.xpath("//div[@id='topyet5logo']"));
                      File f = element.getScreenshotAs(OutputType.FILE);
                      File logo = new File("logo.png");
                      FileUtils.copyFile(f, logo);
                      driver.quit();

                      }
                      }


                      Output :- As of now i am getting the error message as below.


                      [RemoteTestNG] detected TestNG version 7.0.1
                      java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
                      at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:111)
                      at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
                      at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


                      Solution 

                      1.  Update the version for TestNG from 7.0.1 to some previous version like 6.10..
                      2. Note i have change the  version coz my eclipse version is not update..

                      Suggestion

                      if you are using an older version of eclipse then use older version of testNG
                      for new version use current testNG releases.:



                      Please let me know if this helps..

                      Thanks