Monday, August 9, 2010

How to do JUnit Testing Example

JUnit – Testing
JUnit is a simple Java testing framework to write tests for you Java application. This tutorial gives
you an overview of the features of JUnit and shows a little example how you can write tests for
your Java application.
General
Author:
Sascha Wolski
Sebastian Hennebrueder
http://www.laliluna.de/tutorials.html – Tutorials for Struts, EJB, xdoclet and eclipse.
Date:
April, 12 2005
Software:
Eclipse 3.x
Junit 2.x
Source code:
http://www.laliluna.de/assets/tutorials/junit-testing-source.zip
PDF Version
http://www.laliluna.de/assets/tutorials/junit-testing-en.pdf
What is JUnit
JUnit is a simple open source Java testing framework used to write and run repeatable automated
tests. It is an instance of the xUnit architecture for unit testing framework. Eclipse supports
creating test cases and running test suites, so it is easy to use for your Java applications.
JUnit features include:
• Assertions for testing expected results
• Test fixtures for sharing common test data
• Test suites for easily organizing and running tests
• Graphical and textual test runners
What is a test case
A test case is a class which holds a number of test methods. For example if you want to test some
methods of a class Book you create a class BookTest which extends the JUnit TestCase class and
place your test methods in there.
How you write and run a simple test
1. Create a subclass of TestCase:
public class BookTest extends TestCase{
//..
}
2. Write a test method to assert expected results on the object under test:
Note: The naming convention for a test method is testXXX()
public void testCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
3. Write a suite() method that uses reflection to dynamically create a test suite containing all the
testXXX() methods:
public static Test suite(){
return new TestSuite(BookTest.class);
}
4. Activate the JUnit view in Eclipse (Window > Show View > Other.. > Java > JUnit).

You find the JUnit tab near the Package Explorer tab. You can change the position of the tab by
drag and drop it.
5. Right click on the subclass of TestCase and choose Run > JUnit Test to run the test.
Using a test fixture
A test fixture is useful if you have two or more tests for a common set of objects. Using a test
fixture avoids duplicating the test code necessary to initialize and cleanup those common objects
for each test.
To create a test fixture, define a setUp() method that initializes common object and a tearDown()
method to cleanup those objects. The JUnit framework automatically invokes the setUp() method
before a each test is run and the tearDown() method after each test is run.
The following test uses a test fixture:
public class BookTest2 extends TestCase {
private Collection collection;
protected void setUp() {
collection = new ArrayList();
}
protected void tearDown() {
collection.clear();
}
public void testEmptyCollection(){
assertTrue(collection.isEmpty());
}
}
Dynamic and static way of running single tests
JUnit supports two ways (static and dynamic) of running single tests.
In static way you override the runTest() method inherited form TestCase class and call the desired
test case. A convenient way to do this is with an anonymous inner class.
Note: Each test must be given a name, so you can identify it if it fails.
TestCase test = new BookTest("equals test") {
public void runTest() {
testEquals();
}
};
The dynamic way to create a test case to be run uses reflection to implement runTest. It assumes
the name of the test is the name of the test case method to invoke. It dynamically finds and
invokes the test method. The dynamic way is more compact to write but it is less static type safe.
An error in the name of the test case goes unnoticed until you run it and get a
NoSuchMethodException. We leave the choice of which to use up to you.
TestCast test = new BookTest("testEquals");
What is a TestSuite
If you have two tests and you'll run them together you could run the tests one at a time yourself,
but you would quickly grow tired of that. Instead, JUnit provides an object TestSuite which runs
any number of test cases together. The suite method is like a main method that is specialized to
run tests.
Create a suite and add each test case you want to execute:
public static void suite(){
TestSuite suite = new TestSuite();
suite.addTest(new BookTest("testEquals"));
suite.addTest(new BookTest("testBookAdd"));
return suite;
}
Since JUnit 2.0 there is an even simpler way to create a test suite, which holds all testXXX()
methods. You only pass the class with the tests to a TestSuite and it extracts the test methods
automatically.
Note: If you use this way to create a TestSuite all test methods will be added. If you do not want all
test methods in the TestSuite use the normal way to create it.
Example:
public static void suite(){
return new TestSuite(BookTest.class);
}
A little example
Create a new Java project named JUnitExample.
Add a package de.laliluna.tutorial.junitexample where you place the example classes and a
package test.laliluna.tutorial.junitexample where you place your test classes.
The class Book
Create a new class Book in the package de.laliluna.tutorial.junitexample.
Add two properties title of type String and price of type double.
Add a constructor to set the two properties.
Provide a getter- and setter-method for each of them.
Add a method trunk for a method equals(Object object) which checks if the object is an instance of
the class Book and the values of the object are equal. The method return a boolean value.
Note: Do not write the logic of the equals(..) method, we do it after finish creating the test method.
The following source code shows the class Book.
public class Book {
private String title;
private double price;
/**
* Constructor
*
* @param title
* @param price
*/
public Book(String title,
double price) {
this.title = title;
this.price = price;
}
/**
* Check if an object is an instance of book
* and the values of title and price are equal
* then return true, otherwise return false
*/
public boolean equals(Object object) {
return false;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
The test case BookTest
Create a new test case BookTest in the package test.laliluna.tutorial.junitexample Right click on
the package and choose New > JUnit Test Case.
In the wizard choose the methods stubs setUp(), tearDown() and constructor().
The following source code shows the class BookTest
public class BookTest extends TestCase {
/**
* setUp() method that initializes common objects
*/
protected void setUp() throws Exception {
super.setUp();
}
/**
* tearDown() method that cleanup the common objects
*/
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Constructor for BookTest.
* @param name
*/
public BookTest(String name) {
super(name);
}
}
Now we want to write a test for the equals(..) method of the class Book. We provide three private
properties, book1, book2 and book3 of type Book.
private Book book1;
private Book book2;
private Book book3;
Within the setUp() method we initializes the three properties with some values. Property book1
and book3 are the same.
protected void setUp() throws Exception {
super.setUp();
book1 = new Book("ES", 12.99);
book2 = new Book("The Gate", 11.99);
book3 = new Book("ES", 12.99);
}
Within the tearDown() method we cleanup the properties:
protected void tearDown() throws Exception {
super.tearDown();
book1 = null;
book2 = null;
book3 = null;
}
Now, add a test method testEquals() to the test case. Within the method we use the assertFalse()
method of the JUnit framework to test if the return-value of the equals(..) method is false, because
book1 and book2 are not the same. If the return-value is false the logic of the equals() method is
correct, otherwise there is a logical problem while comparing the objects. We want to test if the
method compares the objects correctly by using the assertTrue() method. Book1 and Book3 are
the same, because both are an instance of the class Book and have the same values.
The following source code shows the testEquals() method:
public void testEquals(){
assertFalse(book2.equals(book1));
assertTrue(book1.equals(book1));
}
Writing the logic of the equals() method
We have finished the test and now we can add the logic to the equals() method stub. Open the
class Book and add the logic to the equals() method. First we check if the object given by the
method is an instance of Book. Then compare the properties title and price, if they are equal
return true.
public boolean equals(Object object) {
if (object instanceof Book) {
Book book = (Book) object;
return getTitle().equals(book.getTitle())
&& getPrice() == book.getPrice();
}
return false;
}
Create the suite() method
In order to run the test method testEquals() add a method suite() to the class BookTest.
Note: You can also create a separate class where you add the suite() method.
Within the method create a new instance of TestSuite and use the method addTest(..) to add a
test. Here we use the dynamically way to add a test to a TestSuite.
The method looks like the follows:
public static Test suite(){
TestSuite suite = new TestSuite();
suite.addTest(new BookTest("testEquals"));
return suite;
}
Run the test
After finishing all test methods we want to run the JUnit test case. Right mouse button on the class
BookTest and choose Run As > JUnit Test.
On the JUnit view (Menu Windows -> show view) of Eclipse you can see how many runs, errors
and failures occurred.

Types of JDBC Drivers

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)


4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver

JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.


Type 1: JDBC-ODBC Bridge

Advantage

The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available.

Disadvantages

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver

Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.


Type 2: Native api/ Partly Java Driver

Advantage

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.

Disadvantage

1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.


Type 3: All Java/ Net-Protocol Driver

Advantage

1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver

The Type 4 uses java networking libraries to communicate directly with the database server.


Type 4: Native-protocol/all-Java driver

Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Disadvantage

With type 4 drivers, the user needs a different driver for each database.






Friday, August 6, 2010

The Exception Hirarchy in Java


The rationale behind the hierarchy is as follows:

  • Exception subclasses represent errors that a program can reasonably recover from. Except for RuntimeException and its subclasses (see below), they generally represent errors that a program will expect to occur in the normal course of duty: for example, network connection errors and filing system errors.

  • Error subclasses represent "serious" errors that a program generally shouldn't expect to catch and recover from. These include conditions such as an expected class file being missing, or an OutOfMemoryError.

  • RuntimeException is a further subclass of Exception. RuntimeException and its subclasses are slightly different: they represent exceptions that a program shouldn't generally expect to occur, but could potentially recover from. They represent what are likely to be programming errors rather than errors due to invalid user input or a badly configured environment.

Collections hirarchy


We have tried you to make a walk through the Collection Framework. The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection.

The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces.

The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code.

Tuesday, August 3, 2010

Java™Servlet Specification Version 2.3 (pdf) Download


Contents

Status ................................................................................................. 12
Changes in this document since v2.2........................................... 12
Preface ............................................................................................... 14
Who should read this document .................................................. 14
API Reference ............................................................................. 14
Other Java™ Platform Specifications.......................................... 14
Other Important References ........................................................ 15
Providing Feedback..................................................................... 16
Acknowledgements ..................................................................... 16
Chapter 1:Overview.......................................................................... 18
What is a Servlet?........................................................................ 18
What is a Servlet Container? ....................................................... 18
An Example................................................................................. 19
Comparing Servlets with Other Technologies ............................. 19
Relationship to Java 2 Platform Enterprise Edition ..................... 20
Chapter 2: The Servlet Interface ...................................................... 22
Request Handling Methods ......................................................... 22
HTTP Specific Request Handling Methods........................ 22
PROPOSED FINAL DRAFT
5 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000
Conditional GET Support ...................................................23
Number of Instances ....................................................................23
Note about SingleThreadModel ..........................................24
Servlet Life Cycle ........................................................................24
Loading and Instantiation ...................................................24
Initialization........................................................................24
Request Handling ...............................................................25
End of Service ....................................................................27
Chapter 3: Servlet Context ................................................................28
Scope of a ServletContext............................................................28
Initialization Parameters ..............................................................28
Context Attributes........................................................................29
Context Attributes in a Distributed Container.....................29
Resources.....................................................................................29
Multiple Hosts and Servlet Contexts............................................30
Reloading Considerations ............................................................30
Temporary Working Directories ..................................................31
Chapter 4: The Request .....................................................................32
Parameters ...................................................................................32
Attributes .....................................................................................33
Headers ........................................................................................33
Request Path Elements.................................................................34
Path Translation Methods ............................................................35
Cookies ........................................................................................36
SSL Attributes .............................................................................36
Internationalization ......................................................................37
Request data encoding .................................................................37
PROPOSED FINAL DRAFT
Contents 6
Chapter 5: The Response .................................................................. 38
Buffering ..................................................................................... 38
Headers........................................................................................ 39
Convenience Methods ................................................................. 40
Internationalization...................................................................... 40
Closure of Response Object ........................................................ 41
Chapter 6: Servlet Filtering .............................................................. 42
What is a filter ? .......................................................................... 42
Examples of Filtering Components .................................... 43
Main Concepts............................................................................. 43
Filter Lifecycle................................................................... 43
Filter environment .............................................................. 45
Configuration of Filters in a Web Application ................... 45
Chapter 7: Sessions ............................................................................ 48
Session Tracking Mechanisms .................................................... 48
URL Rewriting................................................................... 48
Cookies .............................................................................. 49
SSL Sessions...................................................................... 49
Session Integrity................................................................. 49
Creating a Session ....................................................................... 49
Session Scope.............................................................................. 50
Binding Attributes into a Session ................................................ 50
Session Timeouts......................................................................... 50
Last Accessed Times ................................................................... 51
Important Session Semantics....................................................... 51
Threading Issues ................................................................ 51
Distributed Environments................................................... 51
PROPOSED FINAL DRAFT
7 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000
Client Semantics .................................................................52
Chapter 8: Dispatching Requests ......................................................54
Obtaining a RequestDispatcher....................................................54
Query Strings in Request Dispatcher Paths.........................55
Using a Request Dispatcher .........................................................55
Include .........................................................................................56
Included Request Parameters ..............................................56
Forward........................................................................................56
Query String .......................................................................57
Error Handling .............................................................................57
Chapter 9:Web Applications.............................................................58
Relationship to ServletContext ....................................................58
Elements of a Web Application ...................................................58
Distinction Between Representations...........................................59
Directory Structure ......................................................................59
Sample Web Application Directory Structure.....................60
Web Application Archive File .....................................................60
Web Application Configuration Descriptor .................................61
Dependencies on extensions: Library Files.........................61
Web Application Classloader..............................................62
Replacing a Web Application ......................................................62
Error Handling .............................................................................62
Welcome Files .............................................................................63
Web Application Environment ....................................................64
Chapter 10:Application Lifecycle Events ........................................66
Introduction .................................................................................66
Event Listeners ............................................................................66
PROPOSED FINAL DRAFT
Contents 8
Configuration of Listener Classes ............................................... 68
Listener Instances and Threading ................................................ 69
Distributed Containers................................................................. 69
Session Events- Invalidation vs Timeout..................................... 69
Chapter 11: Mapping Requests to Servlets ...................................... 70
Use of URL Paths........................................................................ 70
Specification of Mappings........................................................... 71
Implicit Mappings .............................................................. 71
Example Mapping Set ........................................................ 71
Chapter 12: Security.......................................................................... 74
Introduction ................................................................................. 74
Declarative Security .................................................................... 75
Programmatic Security ................................................................ 75
Roles ........................................................................................... 76
Authentication ............................................................................. 76
HTTP Basic Authentication ............................................... 76
HTTP Digest Authentication.............................................. 77
Form Based Authentication................................................ 77
HTTPS Client Authentication ............................................ 78
Server Tracking of Authentication Information .......................... 79
Propogation of Security Identity.................................................. 79
Specifying Security Constraints .................................................. 80
Default Policies .................................................................. 80
Chapter 13: Deployment Descriptor................................................. 82
Deployment Descriptor Elements................................................ 82
Deployment Descriptor DOCTYPE ................................... 82
DTD ............................................................................................ 83
PROPOSED FINAL DRAFT
9 Java Servlet 2.3 Specification - PROPOSED FINAL DRAFT• October 20, 2000
Examples .....................................................................................96
A Basic Example ................................................................97
An Example of Security......................................................98
Chapter 14: API Details .....................................................................100
Config.................................................................................... 104
Filter ...................................................................................... 106
FilterConfig ........................................................................... 108
GenericServlet....................................................................... 110
RequestDispatcher ................................................................ 115
Servlet ................................................................................... 117
ServletConfig ........................................................................ 120
ServletContext....................................................................... 121
ServletContextAttributeEvent ............................................... 129
ServletContextAttributesListener.......................................... 131
ServletContextEvent ............................................................. 133
ServletContextListener.......................................................... 135
ServletException ................................................................... 136
ServletInputStream................................................................ 139
ServletOutputStream............................................................. 141
ServletRequest ...................................................................... 146
ServletRequestWrapper ........................................................ 153
ServletResponse .................................................................... 159
ServletResponseWrapper ...................................................... 163
SingleThreadModel............................................................... 167
UnavailableException ........................................................... 168
Cookie ................................................................................... 173
HttpServlet ............................................................................ 179
PROPOSED FINAL DRAFT
Contents 10
HttpServletRequest ............................................................... 185
HttpServletRequestWrapper ................................................. 193
HttpServletResponse............................................................. 200
HttpServletResponseWrapper............................................... 212
HttpSession ........................................................................... 217
HttpSessionAttributesListener .............................................. 222
HttpSessionBindingEvent ..................................................... 224
HttpSessionBindingListener ................................................. 227
HttpSessionContext............................................................... 228
HttpSessionEvent .................................................................. 229
HttpSessionListener .............................................................. 231
HttpUtils................................................................................ 232
Appendix A: Deployment Descriptor Version 2.2............................ 236
Appendix B: Glossary........................................................................ 250

Jakarta Struts A beginner's tutorial


Jakarta Struts A beginner's tutorial

Contents
1 Introduction 3
1.1 A brief overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 The MVC design pattern and its application to Struts . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Who should read this tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Installation 4
2.1 JDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Win32 installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.1 Linux installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3.1 Win32 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.2 Linux Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.3 Con guration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.4 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5 Struts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 Learning by example: your rst Struts application 6
3.1 Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Creating the application workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 The rst page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.1 First draft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.2 A bit of internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Enter the application and create the data source . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.4.1 The JSP form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.4.2 The struts-con g.xml le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4.3 Create the ActionForm and Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4.4 Re ning the login process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.4.5 Creating a data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5 The main menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.6 Adding a user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.7 Get information about a user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4 Conclusion 23


TypingMaster 2010 Free Download




Learn to touch type and you can! TypingMaster Pro for Windows is a personal typing tutor with 5 typing courses, typing tests, dynamic reviews, games and our unique Satellite to track your real-world typing. TypingMaster Pro's optimal learning features adjust training to your personal progress at every stage. Weak spots are pinpointed and rapidly eliminated with additional exercises.

Thanks to this personal approach you can put your new skills into action after only 3 to 5 hours of training. With TypingMaster, you will learn to type fast without typos and save dozens of valuable working hours every year. Better typing will help you get things done!