Saturday, May 16, 2015

Basic Java Tutorials - First Java Program

Basic Java Tutorials For Selenium2.0 - WebDriver


- Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding of Java.
- This reference will take you through simple and practical approach while learning Java Programming language.
- This reference has been prepared for the beginners to help them understand the basic to advanced concepts related to Java Programming language.
- Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware about what is a computer program and what is a computer programming language.

Java - Overview

- Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
- As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE). With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
- Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. 
- Java is guaranteed to be Write Once, Run Anywhere.
Java is:
  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
  • Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
  • Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
  • Portable:Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
  • Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.
  • Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
  • High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • Distributed:Java is designed for the distributed environment of the internet.
  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

History of Java:

James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.

Tools need:

For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
You also will need the following softwares:
  • Linux 7.1 or Windows 95/98/2000/XP operating system.
  • Java JDK 5
  • Microsoft Notepad or any other text editor
This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Java.
First Java Program :

Let's go over the Hello world program, which simply prints "Hello, World!" to the screen.
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }


Description :
The first line defines a class called Main.
public class Main {
- In Java, every line of code that can actually run needs to be inside a class. This line declares a class named Main, which is public, that means that any other class can access it. This is not important for now, so don't worry. For now, we'll just write our code in a class called Main, and talk about objects later on.
- Notice that when we declare a public class, we must declare it inside a file with the same name (Main.java), otherwise we'll get an error when compiling.
The next line is:
public static void main(String[] args) {
- This is the entry point of our Java program. 
- The main method has to have this exact signature in order to be able to run our program.
  • public again means that anyone can access it.
  • static means that you can run this method without creating an instance of Main.
  • void means that this method doesn't return any value.
  • main is the name of the method.
The arguments we get inside the method are the arguments that we will get when running the program with parameters. It's an array of strings. We will use it in our next lesson, so don't worry if you don't understand it all now.
System.out.println("Hello, World!");
  • System is a pre-defined class that Java provides us and it holds some useful methods and variables.
  • out is a static variable within System that represents the output of your program (stdout).
  • println is a method of out that can be used to print a line.




Thursday, September 4, 2014

Element Locator Strategies in Selenium

A. CSS-Selector Strategies :

Q. Why use CSS Selector vs XPath ?

Reasons :

1. Faster script execution
2. More readable
3. CSS is used by jQuery’s locating strategy
4. Don't use XPATH anyways !!!


Syntax for CSS Selector :

  • css=<All below CSS Patterns type>
CSS Selector Patterns :

     CSS-Patterns                                  Meaning
  1. E                        An element of type E
  2. E[foo]                An E element with a "foo" attribute
  3. E[foo="bar"]       An E element whose "foo" attribute value is exactly equal to "bar"
  4. E[foo~="bar"]     An E element whose "foo" attribute value is a list of space separated values, one                             of which is exactly equal to "bar"
  5. E[foo^="bar"]                 An E element whose "foo" attribute value begins exactly with string "bar"
  6. E[foo$="bar"]                 An E element whose "foo" attribute value ends exactly with string "bar"
  7. E[foo*="bar"]                  An E element whose "foo" attribute value contains the substring "bar"
  8. E:nth-child(n)                  An E element, the nth child of its parent.
  9. E:nthlastchild(n)            An E element, the nth child of its parent, counting from the last one.
  10. E:firstchild                     An E element, first child of its parent.
  11. E:lastchild                      An E element, last child of its parent.
  12. E:onlychild                     An E element, only child of its parent.
  13. E:onlyoftype                   An E element, only sibling of its type.
  14. E:empty                         An E element that has no children (including text nodes)
  15. E:active
    E:hover
    E:focus                      An E element during certain user actions : Active/Hover/Focus
  16. E:enabled
  17. E:disabled                 An user interface element E which is enabled or disabled.
  18. E:checked                 An element 'E' is checked or in an  indeterminate state(radiobutton/CheckBox)
  19. E:contains("foo")       An element 'E' containing the SubString "foo" in its textual contents
  20. E#myid                      An element 'E' with ID equal to "myid" without any blank space
  21. E.myClass                  An element 'E' with Class Name equal to "myClass" without any blank space
  22. E:not(S)                     An element 'E' that does not match simple selector 'S'
  23. E F                             An element 'F' descendant of an 'E' element.
  24. E > F                          An element 'F' direct child of an 'E' element.
  25. E + F                          An element 'F' immediately preceded by an 'E' element.
Limitations of CSS Lcators :
  • There are some cases where you cannot locate element using CSS locator. For instance  //*[@value>3]
  • Lack of arithmetic and logical operator/function support as compare to xpath.
  • Text comparison is case sensitive and there is no way to perform case insensitive comparison.
     
    When referring to parent you must be careful, For Example :
    In Xpath :
           //*[./a[contains(.,'Issue 1244')]]
          //li[./a[contains(.,'Issue 1244')]]
  • Both 1 and 2 are will locate element li, having first child a[contains(.,'Issue 1244')]
  • Whereas in CSS :
                li{a:contains(Issue 1244)}
                *{a:contains(Issue 1244)}
Both 3 and 4 locates different elements. 3 is same as 1(assuming there is no other parent li element of li) but 4 locates first element that having child a:contains(Issue 1244) that is document root. There is no way to locate parent precisely.
For IE, Complex CSS might become as slow as XPath.
Conclusions:
  • Element Location strategy should be selected with following preference id, name, link, dom/css/xpath
  • Locators recorded by IDE are not always efficient but you can modify it manually for the best efficient one.
  • Avoid locating parent using CSS or be more careful.

Introduction to Selenium

What is Selenium...?

  • Selenium is an open source (free) automated testing tool ( Suite of softwares : APIs/Plugin..etc) for web applications across different browsers and platforms. It is quite similar to HP Quick Test Pro (QTP) only that Selenium focuses on automating web-based applications.
    • Runs in many Browsers :
      • IE
      • Firefox
      • Chrome
      • Safari
              And Many Operating Systems :
      • Windows
      • Apple OS X 
      • Linux

    • Can be controlled by many Programming Languages  and Testing Frameworks like :
      • Java - Framework :  JUnit, TestNG
      • C# - Framework : NUnit
      • Python - Framework : unittest, pyunit, robot framework
      • JavaScript
      • Objective-C
      • Perl
      • PHP
      • Ruby
    • Programming languages are supported through Selenium Remote Control "drivers." These are libraries made for each language that expose commands from the Selenium API natively in the form of methods/functions.

  What are the Components of Selenium ?

Selenium Components
  • Selenium is not just a single tool but a suite of softwares (APIs/Plugins), each catering to different testing needs of an organization. 
  • Selenium has four components :
    • Selenium Integrated Development Environment (IDE/SIDE)
    • Selenium Remote Control (RC)
    • WebDriver
    • Selenium Grid

Who developed Selenium ?
Key persons who made the contributions for the Selenium Project :
    Jason Huggins
    • Primarily, Selenium was created by Jason Huggins in 2004. An engineer at ThoughtWorks, was working on a web application that required frequent testing. Having realized that the repetitious manual testing of their application was becoming more and more inefficient, he created a JavaScript program that would automatically control the browser's actions. He named this program as the JavaScriptTestRunner.
    • Seeing potential in this idea to help automate other web applications , he made JavaScriptRunner open-source which was later re-named as Selenium Core.

  • Why Selenium RC, NOT Selenium Core :
    • Because of The Same Origin Policy Issue :

    • Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different from where it was launched. Example, the HTML code in www.google.com uses a JavaScript program 'randomScript.js'. The same origin policy will only allow randomScript.js to access pages within google.com such as google.com/mail, google.com/login, or google.com/signup. However, it cannot access pages from different sites such as yahoo.com/search, because they belong to different domains.
    • This is the reason why prior to Selenium RC, testers needed to install local copies of both Selenium Core (a JavaScript program) and the web server containing the web application being tested so they would belong to the same domain.
    • Selenium RC :

      • Paul Hammant ThoughtWork's Engineer  created  a server that will act as an HTTP proxy   to trick  the browser into believing that Selenium  Core  and the web application being tested come  from  the same domain. This system became  known  as the Selenium Remote Control or Selenium 1.

  • Birth of Selenium Grid :
  • Patrick Lightbody
    • Patrick Lightbody developed Selenium Grid to address the need of minimizing test execution times as much as possible. He initially called the system 'Hosted QA'. It was capable of capturing browser screenshots during significant stages, and also of sending out Selenium commands to different machines simultaneously.
  • Birth of Selenium IDE :
  • Shinya Kasatani
    • Shinya Kasatani of Japan created Selenium IDE in 2006, a Firefox extension that can automate the browser through a record-and-playback feature. He came up with this idea to further increase the speed in creating test cases.

  • Birth of WebDriver :
      Simon Stewart
    • Simon Stewart created WebDriver in 2006, when browsers and web applications were becoming more powerful and more restrictive with JavaScript programs like Selenium Core. It was the first cross-platform testing framework that could control the browser from the OS level.
  • Birth of Selenium 2 :
    • In 2008, the whole Selenium Team decided to merge WebDriver and Selenium RC to form a more powerful tool called Selenium 2, with WebDriver being the core. Currently, Selenium RC is still being developed but only in maintenance mode. Most of the Selenium Project's efforts are now focused on Selenium 2.





  • Selenium WebDriver : Introduction of Selenium WebDriver

    What is WebDriver ?
    • WebDriver in selenium is an Interface and it is designed to overcome some limitations of Selenium RC. 
    • WebDriver is a purely object oriented framework that works on OS layer, also utilizes the browser’s native compatibility to automation without using any peripheral entity.
    • WebDriver also supports various web automation framework that allows you to execute your tests/scripts against different browsers, not just Firefox (unlike Selenium IDE).
    • Also known as Selenium-2.0 and used for web as well mobile applications automation.
    •  most extensively used open source automation testing tool and mostly used for regression testing.
    • Selenium WebDriver's development is in process to overcome few limitations and known issues available in selenium WebDriver. 
    • Ref : http://docs.seleniumhq.org/
    WebDriver also enables you to use a programming language in creating your test scripts(not possible in Selenium IDE).

    Some of the limitations imposed by Selenium IDE are:

    • Doesn’t support iterations and conditional statements
    • Doesn’t support loops
    • Doesn’t support error handling
    • Doesn’t support test script dependency

    • You can now use conditional operations like if-then-else or switch-case 
    • You can also perform looping like do-while  complex scripts..etc
    Following programming languages are supported by WebDriver
    • Java
    • .Net
    • PHP
    • Python
    • Perl
    • Ruby
    • Selenium 2 supports most of all browsers to run your test cases and many programming languages like C#, Java, Python, Ruby, .Net, Perl, PHP, etc.. to create and modify your test scripts. 
    • Selenium 2(WebDriver) controls browser directly from operating system level so it is interacting very fast and with more realistic way with browsers. 
    • Major people in world using Selenium webdriver with java.

    WebDriver Vs Selenium RC :


    Difference between WebDriver and selenium RC :
    • Before advent of WebDriver in  2006, there was another, automation tool called Selenium Remote Control.Both WebDriver and Selenium RC have following features : 
    • They both allow you to use a programming language in designing your test scripts.
    • They both allow you to run your tests against different browsers.
    WebDriver :
    • Selenium WebDriver do not require selenium server for running test.
    • WebDriver is using native automation from each and every supported language for running automation scripts on browsers.
    • WebDriver supports web as well mobile application testing so you can test mobile applications (iPhone or Android).
    • Supporting latest versions of almost all browsers.
    • WebDriver controls the browser itself.
    Selenium RC :
    • Required selenium server for running test.
    • Selenium RC is using JavaScripts to drive automation with browser.
    • Selenium RC supports only web application testing.
    • Supporting all browsers but not supporting latest versions.
    • Selenium RC is using javascript to interact and operate on web page




    Architecture :
    WebDriver's architecture is simpler than Selenium RC's :

    • It controls the browser from the OS level
    • All you need are your programming language's IDE (which contains your Selenium commands) and a browser.

       


    Selenium RC's architecture is way more complicated :

    • You first need to launch a separate application called Selenium Remote Control (RC) Server before you can start testing
    • The Selenium RC Server acts as a "middleman" between your Selenium commands and your browser
    • When you begin testing, Selenium RC Server "injects" a Javascript program called Selenium Core into the browser.
    • Once injected, Selenium Core will start receiving instructions relayed by the RC Server from your test program.
    • When the instructions are received, Selenium Core will execute them as Javascript commands.
    • The browser will obey the instructions of Selenium Core, and will relay its response to the RC Server.
    • The RC Server will receive the response of the browser and then display the results to you.
    • RC Server will fetch the next instruction from your test script to repeat the whole cycle.


    Speed :

    When compared to other tools of Selenium suite, WebDriver turns out to be the fastest tool amongst all. The communication is not channelized via any external intervention; rather the tool directly communicates with the browser same as that of any user. Thus, WebDriver takes advantage of the browser’s native compatibility towards automation.

    WebDriver is faster than Selenium RC since it  speaks directly to the browser uses the browser's own engine to control it.




    Selenium RC is slower  sinceit uses a Javascript program called Selenium Core.This Selenium Core is the one that directly controls the browser, not you.
    Real-life Interaction :
    Selenium webdriver tutorial 3
    • Other tools from Selenium suite like Selenium RC don’t communicate directly with the web browser. Client libraries (test scripts written in any programming language) communicate with Selenium Remote Control Server and Remote Control communicates with a Selenium Core (JavaScript Program) which in turn communicates with the web browser. Hence, this sort of twisted communication results as a hindrance on execution speed.
    • WebDriver makes direct calls to the Web browser and the entire test script is executed in this fashion. WebDriver uses the browsers support and capabilities to automation.

                  Selenium webdriver tutorial 1



    • WebDriver interacts with page elements in a more realistic way. For example, if you have a disabled text box on a page you were testing, WebDriver really cannot enter any value in it just as how a real person cannot.

                    Selenium webdriver tutorial 4

    • Selenium Core, just like other Javascript codes, can access disabled elements .In the past, Selenium testers complain that Selenium Core was able to enter values to a disabled text box in their tests.Differences in API.   
    •   Unlike Selenium RC, Selenium WebDriver doesn’t essentially require Selenium Server to be started before launching the test script execution. User can leverage the benefit and may or may not require Selenium Server if he/she desires to perform the test execution on the same machine where the browser is residing.
    Exceptional Cases when Selenium Server is required with WebDriver:
    • When the user wish to execute test scripts on the remote machine.
    • When the user wish to execute test scripts on HtmlUnit Driver.
    • When the user wish to execute test scripts on multiple platforms.

    API :

    • Selenium RC's API is more matured but contains redundancies and often confusing commands. For example, most of the time, testers are confused whether to use type or typeKeys; or whether to use click, mouseDown, or mouseDownAt. Worse, different browsers interpret each of these commands in different ways too!
    •  WebDriver's API is simpler than Selenium RC's. It does not contain redundant and confusing commands.
    • WebDriver offers a wide range of solutions to some potential challenges in Automation Testing. It helps us to deal with complex types of web elements like checkboxes, dropdowns, and alerts with the help of dynamic finders.
      Selenium webdriver tutorial 5
      With the advent of mobile era, WebDriver API has also matured and introduced some of the key technologies to enter this horizon. WebDriver enables user to perform web based mobile testing. It provides two of the essentials drivers to perform web based mobile testing.
      • AndriodDriver
      • IphoneDriver
      Moreover, WebDriver API is fairly simple and easy. It doesn’t include repetitious commands. On the contrary, Selenium RC embodies many of the tautological commands.

    Browser Support :



    Browser Compatibilty

    WebDriver supports diverse range of web browsers and their versions. It supports all the conventional browsers in addition to some unique and rare browsers like HtmlUnit browser unlike Selenium RC and Selenium IDE.

    • WebDriver can support the headless HtmlUnit browser

















    • HtmlUnit Browser executes the test scripts analogous to other browsers except the fact that it runs in the headless mode i.e. GUI-less mode and the user won’t be able to view the test script execution. Said that the test script execution transpires in headless mode, thus the execution speed takes a roll and quickens the execution.
    •  HtmlUnit is termed as "headless" because it is an invisible browser - it is GUI-less.
    • It is a very fast browser because no time is spent in waiting for page elements to load. This accelerates your test execution cycles.Since it is invisible to the user, it can only be controlled through automated means.
    •  Selenium RC cannot support the headless HtmlUnit browser. It needs a real, visible browser to operate on.
    • WebDriver also supports web based mobile testing. Thus it provides AndroidDriver and IphoneDriver to back web based mobile testing.
    Limitations of WebDriver :

    WebDriver Cannot Readily Support New Browsers :

    Remember that WebDriver operates on the OS level. Also remember that different browsers communicate with the OS in different ways. If a new browser comes out, it may have a different process of communicating with the OS as compared to other browsers. So, you have to give the WebDriver team quite some time to figure that new process out before they can implement it on the next WebDriver release.
    However, it is up to the WebDriver's team of developers to decide if they should support the new browser or not.

    Selenium RC Has Built-In Test Result Generator :

    Selenium RC automatically generates an HTML file of test results. The format of the report was pre-set by RC itself. Take a look at an example of this report below.

    WebDriver has no built-in command that automatically generates a Test Results File. 
    You would have to rely on your IDE's output window, or design the report yourself using the capabilities of your programming language and store it as text, html, etc.