Code debugging with watch variables/expression using Eclipse IDE

Here are the steps to do extensive debugging of java code using Eclipse IDE with watch variables, expression and Inspect.

Step1: Enable breakpoint

Set the breakpoint at the line of code or point of method entry from where you would like to start debugging the code. Right click on the left margin of the editor next to the line of code and a context menu pops up. Select toggle breakpoint in the context menu as shown below:

Figure1: Toggle Breakpoint

Step1-enableBreakpoint

 

Step2: Configure the breakpoint to stop execution

To start debugging, the execution should stop at the breakpoint specified. For this click on breakpoint properties (refer Figure1)  and do the following:

  1. Check Hit count
  2. Specify value as 1
  3. Select “Suspend thread” option

This will stop the execution when the program hits the breakpoint.

Step3setBreakpint

 

Step3: Switch to debug perspective

In Eclipse, select Window –>Open Perspective –> Debug as shown below:

Step4 switch to debug perspective

 

Step4: Run in debug mode

Now run the program in debug mode. Select Run –> Debug

Step5 Run in debug mode

Now the program starts running in debug mode and you would see the state of the thread as “running”

Step6 running thread

When the program hits the breakpoint the state of the thread changes from “running” to “suspended

Step7 suspend thread

 

Step5: Debugging the code with Expressions \Watch variables \ Inspect

Now the code stops at the breakpoint. You could use the watch variables / expression to monitor the current value of the debug variable.

Suppose you set the breakpoint at the variable named “counter” and the program stopped at counter variable as shown below:

step8 stops at code\

Add the expression with the variable name “counter” which allows you to monitor the value of the variable as you execute the program:

Step11 watch variableexpressions

You could also right click on the counter variable and select “Inspect” from the context menu

Step12 right click to inspectstepinto

If it is a method then, select the method name and click on “Step Into Selection“. This will allow you to monitor or debug the method execution line by line.

 

Step6: Use F6 key to step into the method

To “step into” the next executable line of code in the current method, press the “F6 Key”. This will pass the program control from the current line to the next executable line of code.

Step9 Press F6 key

 

TestNG – running tests in parallel

If you have several suites to be run, you could run them in parallel at the same time in different threads.

Parallel suites

In command line the ant task suiteThreadPoolSize can be used to run several suites in parallel using org.testng.TestNG as shown below:

java org.testng.TestNG -suiteThreadPoolSize 3 testng1.xml testng2.xml testng3.xml

This command runs the three suites in 3 different threads in parallel

Parallel methods, tests, classes

In testng.xml file, using the attribute parallel inside the suite tag instructs TestNG to runs tests in parallel in different threads. The attribute parallel accepts certain values as outlined below:

<suite name="mysuite" parallel="methods" thread-count="5">
<suite name="mysuite" parallel="tests" thread-count="5">
<suite name="mysuite" parallel="classes" thread-count="5">
<suite name="mysuite" parallel="instances" thread-count="5">

1. parallel=”methods”: TestNG will run all the test methods in parallel in different threads. The dependent methods will also run in different threads but would respect the order that was specified.
2. parallel=”tests”: TestNG will run all the methods in the same test in the same thread but each test will be run in separate threads. This allows to group the thread-safe classes in the same test so that they will run in the same thread while taking advantage of TestNG’s capability to run tests in several threads.
3. parallel=”classes”: TestNG will run all the test methods in the same class in the same thread and each class will be run in separate thread.
4. parallel=”instances”: TestNG will run all the test methods in the same instance in the same thread and each instance will be run in separate threads.

Also, the attribute threadPoolSize of the @Test annotation could be used to run tests in parallel as shown below.

@Test(threadPoolSize=5, invocation-count=10, timeout=10000)
public void testMethod()
{
  System.out.println("Hello");
}

This will invoke the method testMethod 10 times in 5 different threads. The timeout of 10 seconds ensures that the thread is not blocked for more than 10 seconds. The timout applies for both parallel and non-parallel mode.

TestNG groups using include/exclude

TestNG allows to perform groupings of test methods. The methods can be declared to belong to groups and TestNG can be invoked to include/exclude certain set of groups. This provides maximum flexibility to structure the tests in a more intuitive way.

Step1: Declare groups in java class

Suppose we would like to group the test methods into two categories functional and sanity. We declare the methods to belong to either of the two groups using the “groups” attribute of @Test annotation.

public class Test1
{
  @Test(groups={"functional","sanity"})
  public void testMethod1(){
  }
 
  @Test(groups={"sanity"})
  public void testMethod2(){
  }
 
  @Test(groups={"functional","sanity"})
  public void testMethod3(){
  }
}

 

Step2: Specify groups in TestNG.xml file

Suppose we would like to run the sanity tests alone. We specify the groups in the TestNG.xml file using the <groups> tag inside the <suite> or <test> tag as shown below:

<suite name="mySuite" verbose="1">
  <test name="Regression">
    <groups>
      <run>
        <include name="sanity"/>
      </run>
    </groups>
    <classes>
      <class name="sample.Test1"/>
    </classes>
  </test>
</suite>

Inheritance – the Ace of the Object Oriented Programming world

The code is just a junkyard if it is not designed for reuse. Re-usability is very simple if you understand inheritance, a very powerful principle of object oriented programming. For this reason I call inheritance the Ace of the object-oriented programming world.

Here, I explain inheritance with a simple illustration. From the figure below can you list the properties that are common to all the balloons?

 

The below properties are common to every balloon:

  1. Color
  2. Size
  3. Price and so on

These properties that are common to all classes of a given type say balloon is stored in a class called the base class or super class or parent class. Inheritance is a powerful object oriented programming feature that allows a class to reuse the properties and methods of an already existing class while adding its own functionality. It’s the process of creating a new class as an extension of an existing class primarily to enhance the code re-usability. The class that extends is called the derived / sub class and the class getting extended is called the super / base class.

Suppose there is a super class called superBalloon. There are different kinds of balloons such as birthday balloons, balloons that represent a theme like sports or Disneyland and so on. For class inheritance java uses the keyword extends. Now let’s write a small java program for the base class “superBalloon”.

 

package balloonInherit;
 
public class superBalloon
{
	/**
	 * The superBalloon class defines methods and variables common to all balloons such as
	 * size, color and price
	 */
	//commonly used fields in all balloons
	public int size;
        public String color;
	public double price;
	public int number_of_balloons_purchased;
	public double total_cost;
 
	public void purchase(double price, int number_of_balloons_purchased)
	{
		total_cost = (price * number_of_balloons_purchased);
	}
}

A derived class is more specific and can have additional functionality of its own apart from that of the base class. Thus a birthday balloon is a specialized version of the balloon class having a new field called decoration cost specific to it’s type to better suit the needs.

We can also override /replace the behavior of the base class in the derived class. Here, in the below example the birthday balloon inherits the superBalloon class and defines a new field called decoration cost specific to it’s kind. We use the super keyword to reuse the already existing properties of the base class.

package balloonInherit;
 
public class subPartyBalloon extends superBalloon
{
	/**
	 * Since this is a partyBalloon, an additional new field called decoration cost is added
	 * which is specific to this kind of balloon
	 */
 
	public static void main(String args[])
	{
		//Create an object for subPartyBalloon class and invoke the purchase method
                subPartyBalloon bDayBalloon = new subPartyBalloon();
		bDayBalloon.purchase();
	}
 
	public void purchase()
	{
		//Additional property specific to the type partyBalloon
		double decoration_cost = 2.00;
 
		//Reuse the existing properties of the base class using super keyword
		super.size = 20;
		super.number_of_balloons_purchased = 3;
		super.color = "red";
 
		//These are the prices of the balloon depending on it's size
		switch (super.size)
		{
			case 10:
				super.price = 5.00;
				break;
			case 20:
				super.price = 10.00;
				break;
			case 30:
				super.price = 15.00;
				break;
			default:
				System.out.println("Invalid size");
		}
 
		//Invoke the the purchase methods of the super class to calculate the base_cost
		super.purchase(price,number_of_balloons_purchased);
 
		//Since it is a birthday party balloon the additional cost for decoration is added
		total_cost = total_cost + decoration_cost;
 
		System.out.format("The total cost of %d %s birthday balloons is %.2f", number_of_balloons_purchased,color,total_cost);
	}
}

The switch-case control structure decides the price of the balloon based on the input size. Once a matching size is found it assigns value to the price variable and breaks the execution of the switch-case block. The total cost of the birthday balloons is calculated and the output is as below.

OUTPUT:

The total cost of 3 red birthday balloons is 32.00

Now let’s create a java program for another derived class called subThemeBalloon. A theme based balloon has theme and design as additional fields specific to it’s kind. For example to represent the theme of Disneyland, a balloon is designed with the theme Disneyland and with the shape Mickey mouse.

The subThemeBalloon class reuses the existing properties of the base class superBalloon using the super keyword. It also has three additional new fields viz. theme, design and decoration cost specific to it’s kind to better suit the needs.

package balloonInherit;
 
public class subThemeBalloon extends superBalloon
{
	/**
	 * A theme based balloon has theme and design as additional fields. For example to represent
	 * the theme of Disneyland a balloon is designed with the theme Disneyland and with
	 * the shape mickey mouse
	 **/
 
	public static void main(String[] args)
	{
                //Create an object of subThemeBalloon class and invoke the purchase method
                subThemeBalloon themeBalloon = new subThemeBalloon();
		themeBalloon.purchase();
	}
 
	public void purchase()
	{
		//Declare three additional properties that are specific to the type themeBalloon
		String theme = "Disneyland";
		String design = "Mickey Mouse";
		int decoration_cost = 5;
 
		//Reuse the existing properties of the base class using super keyword
		super.number_of_balloons_purchased = 20;
		super.price = 15.00;
 
		//Invoke the purchase method of the base balloon class to calculate base cost using super keyword
		super.purchase(price, number_of_balloons_purchased);
 
		//Add the decoration cost for the balloon
		total_cost = total_cost + decoration_cost;
 
		//Print the total cost of the balloon
		System.out.format("The total cost of a %s %s balloon is %.2f", theme, design, total_cost);
	}
}

OUTPUT:

The total cost of a Disneyland Mickey Mouse balloon is 305.00

 

This is all about inheritance. Feel free to post any comments /questions.

Six steps for complete test automation with selenium grid

 

The earlier article “Crucial aspects of browser compatibilty testing with Selenium Grid” gives insight into browser compatibility testing andthe architecture of one of the most popular browser compatibility testing tools, selenium grid. Nowlet‘sget our hands dirty with test automation using Selenium Grid.

 

Pre-requisites:

The practice exercise in this article requires Eclipse, TestNG, ant, Java, Selenium RC and Selenium Grid. You can execute the code on your favorite platform. For this demo I am using ubuntu as platform.


Installation of Selenium Grid:

Please refer the documentation in seleniumhq for selenium grid download and installation instructions

http://selenium-grid.seleniumhq.org/step_by_step_installation_instructions_for_windows.html
http://selenium-grid.seleniumhq.org/get_started.html

Unzip the Selenium Grid folder and execute the below command in the Selenium Grid root directory to check whether it is installed correctly or not:

ant sanity-check

The output should be BUILD SUCCESSFUL

Now let’s get started.


 

Step 1. Launch of selenium hub:

Open a terminal and launch the selenium hub using the below command:

ant launch-hub

The hub is where the selenium remote controls providing the different environments like chrome on ubuntu or IE on Windows register themselves. We can view the list of remote controls registered with the hub at http://localhost:4444/console

Now the available remote controls section in the hub console displays nothing  since we did not start any remote control yet.

 

Step 2. Launch of selenium remote controls:

To start a remote control open a new terminal and issue the below command:

ant launch-remote-control

Then, open the hub console http://localhost:4444/console . The selenium grid hub snapshot displays a remote control on port 5555 for firefox. This is the default environment if we do not specify our own.

We can configure more than one selenium remote control with the same port but more than one remote control cannot run tests on the same port. The reason behind this is simple. For example, more than one person can call the same phone number but cannot talk over the phone to the same person at the same time. Only one call can be answered on a single phone at a time. Similarly it is impossible to run tests in parallel on two selenium remote controls configured with the same port number. We need to configure each remote control with unique port numbers. How do we do this?

If we want to specify our own environment we need to use the Dport and Denvironment options as below:

ant -Dport=5556 -Denvironment=*chrome launch-remote-control

 

Step 3. Automatic environment setup:

Let’s create a bash script for automatically opening up new terminals and launching several remote controls with the desired environment. If you are working on windows you need to create a batch file instead of a bash script. The below script works only on ubuntu platform.

Navigate to the selenium grid directory and create the below bash script. Let’s call it run.sh

#!/bin/bash
gnome-terminal --title="Hub" -x bash -c "ant launch-hub"
sleep 150
echo "10 seconds wait over"
gnome-terminal --tab --title="Chrome" -x bash -c "ant -Dport=5555 -Denvironment=*chrome launch-remote-control" &amp;
gnome-terminal --tab --title="Firefox" -x bash -c "ant -Dport=5556 -Denvironment=*firefox launch-remote-control" &amp;
gnome-terminal --tab --title="Opera" -x bash -c "ant -Dport=5557 -Denvironment=*opera launch-remote-control"

The bash script opens a new gnome terminal called “Hub” and launches the selenium hub. It sleeps for 150 seconds waiting for the hub to get started. Depending on the time taken you can change the sleep period. The script then opens three other new terminals and registers three remote controls with the respective environments specified. On execution of the script the below output is got on http://localhost:4444/console page.

Now the environment is setup for selenium grid automation. Let’s write a simple selenium grid program.

 

 

Step 4. Creating a java project called giftShop:

 

Suppose you would like to cheer up your friend on her birthday and give her the best birthday party of all time. You are planning  to celebrate your friend’s birthday with balloons, cakes, ice creams and of course a birthday gift!. You are going to surprise your friend with “I have got something for you” from www.gifts.com in such a way that no one can ever put a price tag on the friendship. Let’s write a selenium program to test the display of birthday gifts page on www.gifts.com website on multiple browsers.

 

  1. In Eclipse create a new java project called “giftShop”. Click on Next button and click on the “Libraries” tab. Click on “Add External JARs” button. Select the testng and selenium server JAR files as below and click on finish button.

 

 

2. Now create a new TestNG class inside the giftShop project. In the source folder field, browse to /giftShop/src. Give the package name as giftShop and class name as giftBox. Click on finish button.

Step 5. Enable testing in parallel mode in multiple browsers:


Right click on the giftShop project. Click on “Convert into TestNG” option. “Generate testng.xml” window will get displayed. This option will be available only if the TestNG plugin for eclipse is installed. Select “tests” in parallel mode dropdown and click on Finish button.

 

To organize the project structure create a folder called config and place the generated testng.xml file in it.

In the testng.xml file we just created, specify the browser and port names with which we have configured our selenium remote control as in the below piece of code.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">
	<test name="Chrome">
		<parameter name="selenium.host" value="localhost"/>
		<parameter name="selenium.port" value="5555"/>
		<parameter name="selenium.browser" value="*chrome"/>
		<parameter name="selenium.url" value="http://www.gifts.com/"/>
		<parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
		<classes>
			<class name="giftShop.giftBox" />
		</classes>
	</test>
	<test name="Firefox">
		<parameter name="selenium.host" value="localhost"/>
		<parameter name="selenium.port" value="5556"/>
		<parameter name="selenium.browser" value="*firefox"/>
		<parameter name="selenium.url" value="http://www.gifts.com/"/>
		<parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
		<classes>
			<class name="giftShop.giftBox" />
		</classes>
	</test>
	<test name="Opera">
		<parameter name="selenium.host" value="localhost"/>
		<parameter name="selenium.port" value="5557"/>
		<parameter name="selenium.browser" value="*opera"/>
		<parameter name="selenium.url" value="http://www.gifts.com/"/>
		<parameter name="bdayLink" value="//li[@id='nav-oc']/div/ul[3]/li[3]/a/b"/>
		<classes>
			<class name="giftShop.giftBox" />
		</classes>
	</test>
</suite>

Step 6: Writing selenium grid program:

This selenium grid program will start selenium on chrome, firefox and opera. It would open up the www.gifts.com website and click on birthday as occasion. It asserts whether the landing page displays the birthday gifts in all the three browsers as expected.

 

package giftShop;
 
import org.testng.annotations.Test;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
 
public class giftBox 
{
	Selenium selenium;
 
	//Declaration of variables used in this program
	String strTimeout="30000";
	String bdayTitle="Birthday Gifts - Birthday Gift Ideas from Gifts.com";
	int intsleepTime=15000;
 
    @BeforeClass
    //Reads the values of host, port, browser and url "www.gifts.com" from testng.xml
    @Parameters({ "selenium.host", "selenium.port", "selenium.browser", "selenium.url" })
    public void beforeClass(String host, String port, String browser, String url)
    {
        selenium = new DefaultSelenium(host, Integer.parseInt(port),browser, url);
        selenium.start();
        selenium.open("");
        selenium.windowMaximize();
        selenium.windowFocus();
        selenium.deleteAllVisibleCookies();
    } 
 
    @Test
    @Parameters({ "bdayLink" })
    public void testB(String bDayGift)
    {
        try
        {
        	//Click on birthday as occasion on www.gifts.com website
        	selenium.click(bDayGift);
        	selenium.waitForPageToLoad(strTimeout);
 
        	//Verify that the birthday gift items page is displayed
        	Assert.assertEquals(bdayTitle, selenium.getTitle());
            Thread.sleep(intsleepTime);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } 
 
    @AfterClass
    public void afterClass() 
    {
        selenium.close();
        selenium.stop();
    } 
}

Running the test case:

Please do the following to run the selenium grid test case (after the hub and RCs are launched):
1. Right click on the testng.xml file
2. Click on Run as “TestNG Suite”

Please feel free to post any comments or ask questions.