Thursday, February 24, 2011

Java Class


What is a Class:
  • In object-oriented programming, a class is a construct that is used as a blueprint (or template) to create objects of that class. This blueprint describes the state and behavior that the objects of the class all share. An object of a given class is called an instance of the class. The class that contains (and was used to create) that instance can be considered as the typeof that object, e.g. an object instance of the "Fruit" class would be of the type "Fruit"
  • A class is a representation for a conceptual grouping of similar terms. For example, a computer could be represented as a class which would have many subclasses such as personal computers, mainframes, workstations, etc.
  • Java classes contain fields and methods.
  • A class is simply a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint can be used to build multiple buildings, a class can be used to create multiple copies of an object.

Java Class Syntax:


Following is the syntax of Java class.


[public] class class-name [inheritance-specification] {

    [field-list;]
    [constructor-list;]
    [method-list;]
}

Types of Java Class:

Java possesses five different types of class construct and if one is to develop quality software it is important to know where to use each type. It can sometimes be difficult to know exactly which variant should be used in a particular situation as often more than one will fit. To make matters worse there are generally many ways that a particular problem can be solved. This article will discuss the various class types and give indicators as to when they should be used.

Top Level Classes

A top level class is the one that all Java developers will be familiar with as without it one can not develop software at all. A typical top level class can be seen below:
package example; public class Foo {     public static void main(String[] args) {     } }
This is the simplest, runnable, top level class that could be developed and lives in a file called Foo.java. Without actually checking I would guess that 90% or more classes are top level. Each class encapsulates some data or functionality that logically belongs on its own. If in doubt about which type of class to use a top level class is probably the safest choice as it will be easier to correct any mistakes later.


Static Member Classes

Static member classes (sometimes called static inner classes although they aren't strictly inner) are the first and most common type of nested class. A nested class is defined inside the body of an enclosing class and should only be present to assist the enclosing class. There is no limit to the depth of the class nesting but it is uncommon to see more than one level and very uncommon to see more than two (in more years than I care to think about developing Java I have never seen a triple nested class).
A very simple static member class is shown below. As with the top level class this is as simple as it can be and is just to show the syntax:
package example;
public class Nest {
    
private static class Nested {
        
    }    
}
Static member classes can be thought of as regular classes that are simply defined inside another class. They have complete access to all the enclosing classes static member variables and functions. All the rules regarding accessibility of the member class are the same as for any other static member of the class. So, for instance, if it's private only the enclosing class can access it.
package example;
public class Nest {
    
    
private static String var = "foo";
    
    
private static class Nested {
        
public Nested() {
            
var = "bar";
        
}
    }    
}
The most common use of static member classes is as an auxiliary class that only makes sense when used in conjunction with its enclosing class. An example of this is in the Java library is in he Map interface which includes the Map.Entry static interface. Although this example uses interfaces rather than classes the intention is exactly the same. Interfaces are used in order to make it easier to switch to a different implementation at a later date.

Non-Static Inner Classes

There is only one small difference between the declaration of a static and non-static member class but in terms of functionality the difference is huge. To define a non-static inner class use the same syntax as for static member classes but don't include the static key word. For Example:
package example;
public class Nest {
    
    
private String var = "foo";
    
    
private class Nested {
        
public Nested() {
            
var = "bar";
        
}
    }    
}
The most important difference between static member classes and non-static inner classes can be seen in this example. Each instance of the inner class is implicitly associated with an instance of its enclosing class. This allows the inner class to directly access the non-static member variables and functions of its enclosing instance. Since a non-static inner class maintains a reference to its enclosing class an instance of a non-static inner class can not be created unless there is an instance of the enclosing class. Instances of the inner class maintain a reference to their enclosing instance which is assigned automatically upon object creation. If your member class doesn't require access to the enclosing instance make it static to save resources.
Non-static inner classes are useful as adaptors that allow a class to appear to be something else. For example one can view the keys in a Map as a Set. This is handled by the creation of an inner class that implements the Set interface which is then returned to the user. Iterators are a similar example. When one requests an Iterator from a collection what one receives is an inner class that implements the iterator interface. The class itself needs to be non-static so that it can access the contents of the enclosing instance.
Due to the restriction that a non-static inner class can't exist without an enclosing instance it is uncommon to see non-static inner classes that aren't private or at least package protected. Static member classes, in contrast, are frequently public.

Anonymous Classes

Anonymous classes are one of the strangest constructs in the Java language and many new developers have trouble getting their head around exactly what is happening. Once anonymous classes are properly understood, however, they open a world of possibilities for quickly solving simple routine problems. The most common use of anonymous classes is with GUI development where they are attached as listeners to the various widgets. Probably the second most common use of anonymous classes is as filters and comparators. The example below shows a simple comparator:
package example;
import java.util.Collections;import java.util.Comparator;import java.util.LinkedList;import java.util.List;
public class Comp {
    
    
public Comp() {
        
List<String> foo = new LinkedList<String>();
        Collections.sort
( foo, new Comparator<String>() {
            
public int compare( String s1, String s2 ) {
                
return s1.compareTo( s2 );
            
}
        })
;
    
}
}
In the above example the anonymous class is an implementation of the Comparator interface that is used to order the List foo. The class is anonymous because it has no name and can't be referenced. In this situation the class is said to be used as a function object.
Anonymous classes can also be process objects such as Runnables or Threads and they can also be used in static factory methods where we want to view one object as if it is another by wrapping it in a class that implements a different interface.
Anonymous classes are a very powerful tool in the developers arsenal but it is important that they aren't over used or overly complex. A long anonymous class can quickly clutter a top level class making it difficult to see where one ends and the other begins. Generally speaking try and keep anonymous classes to a maximum of one screens worth of code or about 40 lines.

Local Classes

Local classes are by far the most uncommon class type to be used in the Java language. In fact I don't actually remember ever seeing one. For those interested an example is show below:
package example;
public class Enclosing {
    
    
public Enclosing() {
        
class Local {
            
public Local() {
                
System.out.println( "In local class...");
            
}
        }
        
new Local();
    
}
}
A local class is declared inside a method body (member classes are declared inside the class). It is only accessible to the method it is declared in which makes local classes less generally useful than non-static inner classes. If used in a non-static setting they acquire a reference to their enclosing class. There are some uses for local classes in situations where there isn't an interface already defined so an anonymous class would be difficult or impossible to use.

Wednesday, February 23, 2011

Introduction to Java

What is Java:

  • Java is a computer programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform.
  • It enables programmers to write computer instructions using English based commands, instead of having to write in numeric codes. 
  • It’s known as a “high-level” language because it can be read and written easily by humans. 
  • Like English, Java has a set of rules that determine how the instructions are written. 
  • These rules are known as its “syntax”. Once a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute.
  • The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities.
  • Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture.
  •  Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible.
  •  It is intended to let application developers "write once, run anywhere". Java is currently one of the most popular programming languages in use, and is widely used from application software to web

Running/Opening Eclipse IDE

1. Run eclipse by double clicking on “eclipse.exe”
Figure: Eclipse IDE exc
2. From the "Workspace Launcher", choose a "workspace" (It is the folder where your projects files will be stores) Ex: D:\EclipseWorkSpace\. Click on "OK" button.
Figure: Eclipse Workspace
3. You will see a Eclipse Welcome Screen. Click on "Workbench", which is highlighted in the following figure.
Figure: Select Workbench
4. And then you will see the eclipse workbench screen
Figure: Eclipse Workbench Screen

Tuesday, February 22, 2011

Installing Eclipse

1. Goto http://www.eclipse.org/ and click on the big download button
Figure: Eclipse Download Link
2. Download the "Eclipse IDE for Java Developers" 
Figure: Eclipse for Windows OS
3. Download the zip file and save it to a folder

4. Unarchive the zip file. The Eclipse folder should look like this.
Figure: Downloaded Eclipse Folder
Thats it, you have downloaded the Eclipse IDE

Monday, February 21, 2011

Installing Selenium RC

1. You can download Selenium RC 1.0.3 from here

2. Save it to C:\Selenium

3. Unzip this into a folder of the same name as the the archive
Figure: Downloaded Selenium Directory
4. Now the C:\selenium folder should look like this.

Figure: Contents OF Selenium RC
Overview of the contents of Selenium

We can see the extracted archive Selenium Remote Control has a lot of folders extracted.

There are two main folder types here:
• specific language client drivers
• selenium server

Each of the supported languages has a client driver. You can see from the list of folders that the
Selenium distribution supports:
• Microsoft .Net
• Java
• Perl
• PHP
• Python and
• Ruby

The client drivers are what we use in our tests to communicate with Selenium-RC. We use the client drivers because our tests act as clients, which communicate with the server, in order to execute commands through the browser.

The client drivers contain the source code, tests, documentation and libraries that we need to work with the Selenium tests.

The selenium server directory has the documentation, source code, tests and executables for working with the Selenium server.

Thursday, February 10, 2011

Selecting All values from a drop down list box

To select all values from the drop down list box we use "storeSelectOptions" command. Following is the example for the same.

Example for "storeSelectOptions" Selenese command:

Just copy paste the following script into your Selenium IDE and use "Google.com" as the base URL.

<tr>
    <td>open</td>
    <td>/</td>
    <td></td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>link=Advanced search</td>
    <td></td>
</tr>
<tr>
    <td>storeSelectOptions</td>
    <td>tbs</td>
    <td>test</td>
</tr>
<tr>
    <td>echo</td>
    <td>${test}</td>
    <td></td>
</tr>

Generating Random String in Selenium IDE

Following is the Selenese command to generate random String in Selenium IDE. It will generate a random string of length 3. It can be varied by changing the length in the for loop.



<tr>
    <td>store</td>
    <td>javascript{var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'; var randomstring = ''; for (var i=0; i&lt;3; i++) { var rnum = Math.floor(Math.random()*chars.length); randomstring += chars.substring(rnum,rnum+1); }}</td>
    <td>randomstring</td>
</tr>

<tr>
    <td>echo</td>
    <td>${randomstring}</td>
    <td></td>
</tr>

Wednesday, February 9, 2011

Generating Random numbers in Selenium IDE

Following is the Selenese command to generate random numbers in Selenium IDE.



<tr>
    <td>storeEval</td>
    <td>javascript{Math.floor(Math.random()*11)}</td>
    <td>randomnumber</td>
</tr>
<tr>
    <td>echo</td>
    <td>${randomnumber}</td>
    <td></td>
</tr>

JUnit Framework

Creating Test cases using Selenium RC and JUnit

1. Open Eclipse IDE

2. Create a Java Project and name it as JUnitTestProject

3. Create the following folders under "JUnitTestProject" project
  • tests
  • lib
  • config
   

Tuesday, February 1, 2011

Simple Example to Execute TestNG tests

Simple Example to Execute TestNG tests

This section will begin with a simple example which will illustrate the basic concepts involved in testing with TestNG.

1. By convention we will create HelloWorld class and we will invoke the TestNG through command line. Create a test folder folder in C drive Ex: C:\TestNG-Examples.


public class HelloWorld{

@Test
public void HelloWorld()
System.out.println("Hello World");
}
}

Monday, January 31, 2011

Introduction to TestNG

Introduction:

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalists that make it more powerful and easier to use.

TestNG is a testing framework designed to simply a broad range of testing needs, from unit testing (testing a class in isolation of the others) to in integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers)

Installing TestNG

Installing TestNG

Downloading and Installing TestNG is same of that of JUnit. (Refer this link before moving further)

1. Download testng-5.9-jdk15.jar file

2. For the purpose of this tutorial, download testng-<version-number>.jar file into C TestNG folder of C drive.

3. Now you have extracted TestNG, you need to add testng-5.9-jdk15.jar to your classpath. This enables the Java compiler to resolve where and what TestNG is.

Installing TestNG in Eclipse IDE

Installing TestNG in Eclipse IDE

Following steps will guide you to install TestNG in Eclipse IDE.

1. Open Eclipse 

2. Click on "Help" menu, select "Install New Software..." (see the following figure)
Figure: Select "Install New Software" from Help menu
3. In the "Install" wizard, click on "Add" button

4. In the "Add Repository" window, enter Name as "TestNG" and Location as "http://beust.com/eclipse", click on "OK" button

5. TestNG will be added into the "Install" wizard, select "TestNG" checkbox and click on "Next" button.

Figure: Install Wizard
6. Click on again "Next" button from "Install Details" page.

7. In the "Review Licenses" page, select "I accept the terms of the license agreement" radio button and click on "OK" button

Eclipse will start installing the latest version of "TestNG"

8. The wizard will ask you to re-start eclipse.

Now, TestNG has installed sucessfully. You can create your unit test cases by using TestNG.

Friday, January 28, 2011

Connecting SQL Server using Windows Authentication

Connecting SQL Server using Windows Authentication


Step 1: Setup ODBC


To set up ODBC
a. goto Control Panel
b.Double click on "Administrative Tools"
c. Double click on "Data Sources (ODBC)"
d. Under "User DSN" tab, click on "Add" button
e. In "Create New Data Set" window, select "SQL Native Client"
f. In "Create a New Data Source to SQL Server" window, enter data source name, select your db server for which you want to connect from the "Server" drop down list
g. Click on "Next" button
h. In the next window, select the 1st option i.e., "With Integrated Windows authentication", click on "Next" button
i. Click on "Finish" button


This newly added data source should be available for you.


Step 2: Adding "sqljdbc4.jar" file


Add "sqljdbc4.jar file to your project library.

Step 3: Write the following Class to connect DB

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Database{
public Connection conn = null;
private String dbName = null;

public Database(){
}

public Database(String dbName, String dataSourceName){
this.dbName = dbName;
try{
      class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       this.conn = DriverManager.getConnection(dataSourceName)
      System.out.println("Connected Successfully");
     }

catch(ClassNotFoundException e){
e.printStackTrace();
}

catch(SQLException e){
e.printStackTrace();
}
}

Step 4:  Execute it from Main Method:

import java.sql.*;

public class Main{

public static void main(String[] args)
{
try{
     Database db = Database("SQLEXPRESS", "jdbc:odbc:MySQLDB");
     }
catch(Exception e){
e.prntStackTrace();
}

Output: Connected Successfully

Thursday, January 27, 2011

Running Selenium IDE Test Suite

Running Test Suite

Test suite prepared in the Selenium IDE can be run in a several way. Look at the Following are 3 methods with the help of which you can run the test suite prepared in the selenium IDE

1. From the Selenium IDE:

a. We can run the designed selenium test suite from the selenium IDE itself. Please refer Building Test Suite in Selenium IDE link which will guide you how to prepare selenium test suite.

b. Open the saved selenium test suite. Click on File > Open Test Suite. This open all your test cases.

c. Click on "Play entire test suite" button (First green arrow button). 

Selenium will run all your test and produces the test results in the "Results" pane.

2. From Selenium RC

We can run the same selenese test scripts by using Selenium RC server.
To run the HTML test suite, we use -htmlSuite command.

-htmlSuite requires you to specify:
The syntax of -htmlSuite command is:
-htmlSuite(browserString, startURL, suiteFile, suiteFile, resultFile)

where,
  • browserString is the browser name ex: "*firefox"
  • startURL is the base URL ex: http://demo.actitime.com/
  • suiteFile - Test Suite file lcation ex:  C:\SIDE
  • resultFile - You need to create a blank html file named results.html and specfify the path of thos file. Ex: C:\SIDE\results.html
Follow these steps to run the suite:

1. Create a HTML file that will keep your test results Ex: C:\SIDE\results.html
2. Oprn a command link
3. move to the selenium-server.jar location Ex: cd D:\selenium-remote-control-1.0.3\
4. Now the -htmlSuite command with required arguments.
Ex: java -jar selenium-server.jar -port 4444 -htmlSuite *firefox, "http://www.google.com" "c:\SIDE\ActiTimeTestSuite.html" "C:\SIDE\results.html"

You will see Test Runner will open and start running your tests in firefox browser

After the test script is done, you can check the test results in the HTML file you provided as argument i.e., C:\SIDE\results.html

Your test results should look like this:

Figure: Test Results




Monday, January 24, 2011

Building Test Suite in Selenium IDE

Test Suite:

A test suite is a collection of test cases which is displayed in the leftmost pane in the IDE. The test suite pane can be manually opened or closed via selecting a small dot halfway down the right of the pane (whic is the left edge of the entire Selenium-IDE window if the pane is closed).

The test suite pane will be automatically opened when an existing test suite is opened or when the user selects the New Test Case item from the File menu. In the later case, the new test case will appear immediately below.

Creating Test Cases:

Before creating a test cases, login to following application and click through the links http://demo.actitime.com/

Now create a test case. To create a test case,
  1. Open Selenium IDE
  2. Go to File menu > New Test Case
  3. Click on "Record" button
    • Open http://demo.actitime.com/
    • Enter Username as "user"
    • Enter Password as "user"
    • Click on "Login" button
    • Once you enter into the application, right click on the firefox box (within the application and select "assertTitle actiTIME - Enter Time-Track"
    • Click on "Stop Recording" button 
  4. Now to save a test case, select File > Save Test Case
  5. Save this test case with name "01_Login.html" into C:\SIDE folder (or any folder you want)
  6. You can debug/verify this test case, by running it.
Similarly record some test cases by clicking on "Tasks" and "Reports" link and assert the page. Save those test cases as "02_Tasks.html" and 03_Reports.html"

Creating a Test Suite:

To create a test suite in Selenium IDE
  1. Go to File menu > New Test Suite
  2. To add the test cases: Go to File > Add Test Case
  3. Navigate to the location of your test case (in our case C:\SIDE)
  4. Select 01_Login.html, click on "Add"
  5. Repeat steps 2-4 for more test cases
  6. To save your test suite, select File > Save Test Suite and name it as ActiTimeTestSuite.html
Your test suite should look like this.

Figure: Test Suite in Selenium IDE


Installing AutoIt

Installing AutoIt

1. Goto following site - http://www.autoitscript.com/autoit3/downloads.shtml

2. Click on the highlighted link shown in the figure and save to your desktop.

Figure: AutoIt down loader link

3. You are ready to start installing AutoIt. Double click on the AutoIt installer file you downloaded. This will begin the installation process.

4. The first window that appears is the welcome screen for the AutoIt installer. This provides you with some basic information about version of AutoIt that you are installing. Click the Next > button when you are ready to continue.

5. The next screen is the licensing agreement. Read through it carefully to ensure that you agree with it. When you are finished reading it, click on I Agree to continue.

6. In the third screen, you are provided with a couple of options. The window is asking you what you want to happen when you double click on a file that has a.au3 extension. Files with .au3 extension are typically scripts written in AutoIt. If you select Run the script, the script dile you have just double clicked will run the contents of the script. If you select Edit the script, the file will open up in your default AutoIt editor.

Once you have decided on the option you would like to use, select it and click on the "Next" button.

7. Next screen will ask you to select "Choose Components". Select "Full" and click on "Next" button.

8. The next window prompts you for a location to install "AutoIt". By default, it selects C:\Program Files\AutoIt3. If you would like to install it somewhere else, you can try it. Once you decide the location of AutoIt, click the Install button to begin the installation.

9. While AutoIt is installing you will see a progress bar indicating how far along the AutoIt installation has progressed.

10. Once the installer has made all of the changed, you will see the final window telling you that AutoIt has successfully installed. Click Finish to complete the installation process.