Monday 17 February 2014

Flow Control, Assertions and Exception Handling

Flow Control, Assertions and Exception Handling
If a method declares an exception in its signature, you cannot use this method without handling the exception - you can't compile the program.
Write code using if, and switch statements and identify legal argument types for these statements.
Consult a text book for the basics of these, if unsure. If you do know the basics, here are a few things to watch out for:



if (result >=0)
if (result > 0)
System.out.println("positive");
else
System.out.println("negative");

if (result >=0)
if (result > 0)
System.out.println("positive");
else
System.out.println("negative");
A good practice is to use blocks with all your if and else statements to avoid this ambiguity.

Number 2
After switch/case construct has executed the correct case, it will continue to execute all those after it (including default: if it is there, after the selected case) on to the end of the switch/case block, unless you put in a break, return or throw statement. This is referred to as "falling through". For example:

switch (a)
{
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
default:
System.out.println("some other number");
}
If a is 1, this will print "one", "two", "three" and then "some other number" in succession. If a is 3, this will print "three" and then "some other number".

In some cases, this kind of behaviour might desirable, but here it isn't. This block of code fixes it:

switch (a) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
default:
System.out.println("some other number");
}
Note that in switch blocks, it is legal to put default: anywhere in the block, it doesn't have to be the last one.
Number 3
The argument for an if() statement must be a boolean or an expression which evaluates to a boolean. A common beginners mistake is to use a single = rather than == to compare values. The following gives a compiler error:

public static void main(String[] args) {
int a=1;
if(a=2) System.out.println("a is two");
}
a=2 assigns the value 2 to a.



The argument for a switch statement must be a byte, a char, a short or an int, or an expression which evaluates to one of those.






Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution.
An loop example:



for(int i=0;i<3;i++){
System.out.println("i is "+i);
for(int j=0;j<3;j++) {
System.out.println("j is"+j);
}
}
Will print:

i is 0
j is 0
j is 1
j is 2
i is 1
j is 0
etc.



Note: Don't get thrown if the for loop uses pre-increment instead of post-increment i.e. for(int i=0;i<3;++j) instead of for(int i=0;i<3;j++). This does not make any difference to the behavior of a for loop.
break will cause the current loop to be abandoned. continue causes execution to skip the rest of the code in the current iteration of the loop, and start at the top of the loop with the next iteration.
These (unlabeled) versions will only affect the execution of loop that they are in. If you have nested loops, and want to break out of, or skip to the next iteration of, an outer loop, from an inner loop, you used the labeled versions. These jump to the wherever the label is, allowing you to break out of, or skip several nested loops, by placing the label in front of the outer loop.
Labels are a name followed by a colon, i.e. ":", placed before the loop.



Write code that makes proper use of exceptions and exception handling clauses (try, catch(), finally) and declares methods and overriding methods that throw exceptions.
Place code which is likely to throw an exception inside a try { } block. Create one or more catch() { } blocks with code to deal with the types of exceptions that might be thrown in the try block. The type of exception goes inside the round brackets of the catch() statement, as you would when declaring a method.

Exceptions are objects, which belong to a class hierarchy. If the exception thrown is an instance of the class, or a subclass of the class, specified in catch(), that catch block is the one executed. Your catch() block therefore can handle a range of exceptions if they are subclasses of the class specified. If you want to handle one specific subclass one way, and all the other subclasses differently, put a catch statement for the specific subclass first, and a more general catch block for the superclass second. Then when an exception is thrown, if the exception is a member of the subclass, that catch block only executes, but if it is a different subclass of the parent class, the general catch block executes. If you put the superclass first, you will get a compiler error.



Declaring exceptions in a method
For example:
void mymethod(int i) throws Exception { }
Methods can throw more than one class of exception, you list all the exceptions after the throws keyword, separated by commas.
Overriding and exceptions
Essentially, a method can throw the same or fewer, but not more, exceptions than the superclass method it is overriding. This has to do with object orientation, if you could broaden the number of exceptions in the subclass method, anything which can deal with the superclass might not be able to deal with the subclass, because the are new exceptions there that it was not designed to handle. You want all members of subclasses to be able to be handled as if there were members of the parent class ("upcasting" or polymorphism).



The hierarchy of exceptions is important here, you can replace a exception class in the overridden method with one or more of its subclasses, but you can't replace it with its superclass. To do this would be to broaden the range of exceptions the method could throw.
To create and throw a specified exception
For example:
throw new SomeKindOfException();
Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).
If an exception is thrown, then the rest of the code in the try block is not executed. If any catch block matches the exceptions class or a super class of the exception, that block executes. If the exception is not caught correctly, then after the finally block executes, the rest of the code in the method is not executed.



finally blocks execute no matter what, in other words, whether the code executes without an exception, or an exception is thrown and successfully caught, or an exception is thrown and not caught. This is useful because, except for code in a finally block, if an exception is thrown and not caught, the execution of the rest method is abandoned.



It is legal to have a try block, followed by a finally block, without any catch blocks.



One thing (probably not important for the exam) which could stop a finally clause from executing, is a call to System.exit(0).



RuntimeExceptions differ from normal exceptions in that they are not required to be declared or handled within a try block. An Error indicates serious problems that a reasonable application should not try to catch. Examples are the VM running out of memory.



Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions.
For more information see: http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html.
The simplest form of assertion consists of the assert keyword followed by an expression which evaluates to a boolean. Example:
assert someObject != null;
If the expression evaluates to false then an AssertionError is thrown. The other form adds a colon followed by a second expression which evaluates to a value of some kind. If the assertion fails, the value is included in the AssertionError for information. Example:
assert someObject != null : "someObject should not be null at this point!";



Assertions may be enabled or disabled. Your code should work correctly in either cases. Do not do anything in an assertion which will have side affects on the behaviour of other parts of your code (with the possible exception of other assertions). Sun do not recommend the use of assertions to verify the correct use of the public API of you classes. Instead a more specific exception such as IllegalArgumentException should be used. However you can perform checks using assertions on the arguments provided to non-public methods, so long as those assertions should remain true regardless of how other classes invoke your API. In other words use assertions to confirm your is doing internally what you intended, rather than to check that it is being used correctly by others.



Identify correct statements about the assertion mechanism.













Tuesday 11 February 2014

Element Locators in Webdriver



In WebDriver automation everything related with web elements as it is web application automation tool.
WebElement is nothing but, all DOM objects appeared in the web page. To do operations with DOM objects/ web elements we need to locate those elements exactly.
WebElement element=driver.findElement(By.<Locator>);
As we've seen in the above statement we have to specify some locator to identify web element.
'By' is the class, in that class we have different static methods to identify elements. Those are,
    By.className
    By.cssSelector
    By.id
    By.linkText
    By.name
    By.partialLinkText
    By.tagName
    By.xpath

See below example
Example:1
      <td class=name> </td>
WebElement td=driver.findElement(By.className("name"));
CSS selector is the one the best ways to locate some complex elements in the page.
See below some examples for easy understanding
Example:1

     <td class=name> </td>
driver.findElement(By.cssSelector("td.name"));     In css selector we can denote class name with dot (.)
                             (or)
driver.findElement(By.cssSelector("[class=name]"))    We can specify the attribute name and its value.

Example:2
    <input id=create>
driver.findElement(By.cssSelector("#create")).sendKeys("test");    shortcut for denoting id is #
                                  ( or )
driver.findElement(By.cssSelector("[id=create]")).sendKeys("test")

Example:3
    <td value=dynamicValue_13232><td>

driver.findElement(By.cssSelector("[value*=dynamicValue]"))     * is for checking contained value
(here value contains dynamicValue)
Example:4
              <div value=testing name=dynamic_2307></div>
driver.findElement(By.cssSelector("[value=testing][name*=dynamic]")); 
If you want to include more attribute values in locator criteria use css locator as above.
By.id
See below example
Example:1
      <td id=newRecord> </td>

WebElement td=driver.findElement(By.id("newRecord"));
here we can specify the id attribute value directly.
By.linkText
See below example
Example:1
      <a onclick=gotonext()>Setup </a>
WebElement link=driver.findElement(By.linkText("Setup"));
This is the best locator for locating links (anchor tags) in your web page.
By.partialLinkText
See below example
Example:1
      <a onclick=gotonext()>very long link text </a>
WebElement link=driver.findElement(By.partialLinkText("very"));
                               (or)
WebElement link=driver.findElement(By.partialLinkText("long link"));

This is the locator for locating links (anchor tags) using partial text it contains .
By.name
See below example
Example:1
      <td name=WebDriver> </td>
WebElement td=driver.findElement(By.name("WebDriver"));
See below example
Example:1
      <td class=name> </td>
WebElement td=driver.findElement(By.tagName("td"));
If you want to get the entire text of web page use below logic.
driver.findElement(By.tagName("body")).getText()
By. XPath
XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications. XPath extends beyond (as well as supporting) the simple methods of locating by id or name attributes, and opens up all sorts of new possibilities such as locating the third checkbox on the page.

One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name.

Absolute XPaths contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. By finding a nearby element with an id or name attribute (ideally a parent element) you can locate your target element based on the relationship. This is much less likely to change and can make your tests more robust.

For instance, conside this page source:
<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>

The form elements can be located like this:

login_form = driver.find_element_by_xpath("/html/body/form[1]")
login_form = driver.find_element_by_xpath("//form[1]")
login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

    Absolute path (would break if the HTML was changed only slightly)
    First form element in the HTML
    The form element with attribute named id and the value loginForm

The username element can be located like this:

username = driver.find_element_by_xpath("//form[input/@name='username']")
username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
username = driver.find_element_by_xpath("//input[@name='username']")

    First form element with an input child element with attribute named name and the value username
    First input child element of the form element with attribute named id and the value loginForm
    First input element with attribute named ‘name’ and the value username

The “Clear” button element can be located like this:

clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']")
clear_button = driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")

Monday 10 February 2014

Working with different drivers like HtmlUnitDriver,Internet Explorer Driver,Firefox Driver,



The existing drivers are the ChromeDriver, InternetExplorerDriver, FirefoxDriver, OperaDriver and HtmlUnitDriver. including their relative strengths and weaknesses There is also support for mobile testing via the AndroidDriver, OperaMobileDriver and IPhoneDriver
While working with selenium webdriver you have an option to choose from multiple webdrivers, such as HtmlUnitDriver, FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver. Each one of them is a separate implementation of the WebDriver interface provided by Selenium.
The first major point to note is that there are two groups of driver implementations. One of those that invoke the actual browser installed on your system and the other that emulates the behavior of another browser. FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver invoke the actual browser installed on the machine; however the HtmlUnitDriver emulates other browsers JS behavior.
This is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit.
·         Fastest implementation of WebDriver
·         A pure Java solution and so it is platform independent.
·         Supports Javascript

 HtmlUnit is a java based framework for testing webApps basically a wrapper around ‘HttpClient’ by Jakarta. HtmlUnit provides UI-Less emulation of browsers to test web applications. The HtmlUnit APIs let you do the typical functions performed in an actual web browser, such as click links, fill forms, invoke web pages, submit values etc. HtmlUnit supports java script and complex AJAX libraries. Javascript is disabled in the HtmlUnitDriver by default, however if it can be enabled if required. The mechanism to enable javascript with the HtmlUnitDriver is as follows:

HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver();
 MyhtmlDriver.setJavascriptEnabled(true);
OR
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(true);

When enabled, the HtmlUnitDriver emulates the java script behavior of Internet Explorer by default. However we can direct the HtmlUnitDriver to emulate the JavaScript behavior of the browser of our choice by invoking the constructor that accepts the browser version. This can be done as follows:
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(BrowserVersion.Firefox_2);
The InternetExplorerDriver is a standalone server which implements WebDriver's wire protocol. This driver has been tested with IE 6, 7, 8 and 9 on appropriate combinations of XP, Vista and Windows 7.

The driver supports running 32-bit and 64-bit versions of the browser. The choice of how to determine which "bit-ness" to use in launching the browser depends on which version of the IEDriverServer.exe is launched. If the 32-bit version of IEDriverServer.exe is launched, the 32-bit version of IE will be launched. Similarly, if the 64-bit version of IEDriverServer.exe is launched, the 64-bit version of IE will be launched.
 The IE driver class ‘InternetExplorerDriver.class’ is located at ‘\org\openqa\selenium\ie\’ directory in the ‘selenium-server-standalone-2.7.0.jar’. To use the InternetExplorerDriver all you need to do is to have the selenium-server-standalone-2.7.0.jar in your CLASSPATH.  The IE driver runs only on windows and supports both 32-bit and 64-bit operations. Depending on the thread that instantiates the InternetExplorerDriver corresponding version of the IE is launched i.e. if the thread instantiating driver is running in 32-bit then the 32-bit version of the IE will be launched and if the thread instantiating driver is running in 64-bit then the 64-bit version of the IE will be launched.

The Internet Explorer driver uses the native or OS-level events to perform various functions on the browser, such as inputs from keyboard and mouse. This approach has both advantages and limitations both. The advantages are that it bypasses the limitations of the Javascript sandbox but there can be issues like the browser window under test might be out of focus.

‘selenium-server-standalone-X.X.X.jar’ contains all the drivers implementing the WebDriver interface of selenium. Hence the 'FirefoxDriver.class' can be found in the ‘\org\openqa\selenium\firefox directory in the selenium-server-standalone-X.X.X.jar. The driver when instantiated is added as an extension to the firefox profile. You can specify the profile with which you want to load firefox session. If no profile is specified then the driver creates an anonymous profile by default.
A profile can be created for the firefox driver as follows:

FirefoxProfile myProfile = new FirefoxProfile();

Multiple operations can be performed on the newly created profile, such as:

myProfile.addExtension(File);
myProfile.clean();
myProfile.getPort();
myProfile.setPort(int port);
myProfile.enableNativeEvents();
myProfile.setPreference(String key, String value); etc...

After creating the your profile you can pass the profile while creating the driver instance as follows:
WebDriver myFireFoxDriver = new FirefoxDriver(myProfile);

This driver is faster than the InternetExplorerDriver and executes the test in real Firefox web browser.