Thread
A thread is a lightweight process which exist within a program and executed to perform a special task. Several threads of execution may be associated with a single process. Thus a process that has only one thread is referred to as a single-threaded process, while a process with multiple threads is referred to as a multi-threaded process. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.
In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime. In single threaded runtime environment, operations are executes sequentially i.e. next operation can execute only when the previous one is complete. It exists in a common memory space and can share both data and code of a program. Threading concept is very important in Java through which we can increase the speed of any application.
Main Thread
When any standalone application is running, it firstly execute the main() method runs in a one thread, called the main thread. If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. The main() method execution can finish, but the program will keep running until the all threads have complete its execution.
Life Cycle of A Thread
1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.
Thread Implementation
I. Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.
II. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:
1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this.
2. The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive.
Daemon threads
Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()
When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.
Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Synchronized blocks place locks for shorter periods than synchronized methods.
Mutual exclusion
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
Welcome to the Java Blog, written by me with the sole purpose of talking about Java & Web technologies. I'm aiming this blog at other Java developers with the deeper aspects of writing code and resolving technical issues. Hopefully I can blog about some really interesting topics as I come across them. Mr. Patricia Seybold said, "If you learn to program in Java, you’ll never be without a job!"
Thursday, March 12, 2009
Wednesday, March 4, 2009
XML and Java Technologies
XML and Java Technologies
* Extensible Markup Language(XML)
XML stands for EXtensible Markup Language. Its a markup language much like HTML. XML was designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is designed to be self-descriptive. XML is a W3C Recommendation
* Java API for XML Processing (JAXP), v 1.3
The Java API for XML Processing, or JAXP for short, enables applications to parse and transform XML documents using an API that is independent of a particular XML processor implementation. JAXP also provides a pluggability feature which enables applications to easily switch between particular XML processor implementations.
To achieve the goal of XML processor independence, an application should limit itself to the JAXP API and avoid implementation-dependent APIs and behavior. This may or may not be easy depending on the application. See this question for more information. JAXP includes industry standard APIs such as DOM and SAX. See these slides (PDF) for more information.
The reason for the existance of JAXP is to facilitate the use of XML on the Java platform. For example, current APIs such as DOM Level 2 do not provide a method to bootstrap a DOM Document object from an XML input document, JAXP does. (When DOM Level 3 provides this functionality, a new version of the JAXP specification will probably support the new Level 3 scheme also.) Other parts of JAXP such as the javax.xml.transform portion do not have any other equivalent XSLT processor-independent APIs.
* Java Architecture for XML Binding (JAXB), v 1.0 and 2.0
Java Architecture for XML Binding (JAXB) provides an API and tool that allow automatic two-way mapping between XML documents and Java objects. With a given Document Type Definition (DTD) and a schema definition, the JAXB compiler can generate a set of Java classes that allow developers to build applications that can read, manipulate and recreate XML documents without writing any logic to process XML elements. The generated codes provide an abstraction layer by exposing a public interface that allows access to the XML data without any specific knowledge about the underlying data structure. In addition to DTD support, future versions of JAXB will add support for other schema languages, such as the W3C XML Schema. These features enable the JAXB to provide many benefits for the developers, which are further explained in the next section.
* JAX-RPC v 1.1
To aid developers in building XML-based requests such as SOAP requests, The JCP is developing the Java APIs for XML based RPC (JAX/RPC). JAX/RPC is used for sending and receiving (including marshalling and unmarshalling) method calls using XML-based protocols such as SOAP, or others such as XMLP (XML Protocol. For more information, see http://www.w3.org/2000/xp/). JAX/RPC isolates you from the specifics of these protocols, enabling rapid application development. There is no longer any need for developers to interact directly with the XML representation of the call.
* JAX-WS v 2.0
JAX-WS (Java API for XML Web Services) is a technology designed to simplify the construction of web services and web service clients in Java. The latest version, JAX-WS 2.0, which is part of the new Java EE 5 platform, provides powerful new tools and techniques to facilitate web service development.
* SAAJ (SOAP with Attachments API for Java)
SOAP with Attachments API for Java (SAAJ) is used mainly for the SOAP messaging that goes on behind the scenes in JAX-RPC and JAXR implementations. Secondarily, it is an API that developers can use when they choose to write SOAP messaging applications directly rather than use JAX-RPC. The SAAJ API allows you to do XML messaging from the Java platform: By simply making method calls using the SAAJ API, you can read and write SOAP-based XML messages, and you can optionally send and receive such messages over the Internet (some implementations may not support sending and receiving). This chapter will help you learn how to use the SAAJ API.
The SAAJ API conforms to the Simple Object Access Protocol (SOAP) 1.1 specification and the SOAP with Attachments specification. The SAAJ 1.2 specification defines the javax.xml.soap package, which contains the API for creating and populating a SOAP message.
* Java API for XML Registries (JAXR)
The Java API for XML Registries (JAXR) API provides a uniform and standard Java API for accessing different kinds of XML Registries. XML registries are an enabling infrastructure for building, deployment, and discovery of Web services.
An abstraction-based JAXR API gives developers the ability to write registry client programs that are portable across different target registries. This is consistent with the Java philosophy of Write Once, Run Anywhere. It also enables value-added capabilities beyond what the underlying registries are capable of. For example, a non-JAXR UDDI client does not have the ability to do taxonomy browsing and taxonomy-aware smart queries, which are available to a JAXR client for UDDI.
* Java API for XML Messaging (JAXM) - Optional
When receiving a web service request from say a business partner, we need a Java API to process XML messages, in a similar way to how we processed SOAP requests using JAX/RPC. The Java API for XML Messaging (JAXM) is a forthcoming specification for interacting with XML messaging standards such as ebXML messaging and SOAP messaging. This API is designed to facilitate the processing of XML message protocols, particularly those where a predetermined “contract” exists (ebXML in particular) to determine the format and constraints of the message. This API will handle all the “envelope” information, such as routing information and the “cargo” manifest, in an intuitive way separate from the actual payload of the message. This allows developers to focus on interacting with the payload and not worry about the other message administrivia.
* Extensible Markup Language(XML)
XML stands for EXtensible Markup Language. Its a markup language much like HTML. XML was designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is designed to be self-descriptive. XML is a W3C Recommendation
* Java API for XML Processing (JAXP), v 1.3
The Java API for XML Processing, or JAXP for short, enables applications to parse and transform XML documents using an API that is independent of a particular XML processor implementation. JAXP also provides a pluggability feature which enables applications to easily switch between particular XML processor implementations.
To achieve the goal of XML processor independence, an application should limit itself to the JAXP API and avoid implementation-dependent APIs and behavior. This may or may not be easy depending on the application. See this question for more information. JAXP includes industry standard APIs such as DOM and SAX. See these slides (PDF) for more information.
The reason for the existance of JAXP is to facilitate the use of XML on the Java platform. For example, current APIs such as DOM Level 2 do not provide a method to bootstrap a DOM Document object from an XML input document, JAXP does. (When DOM Level 3 provides this functionality, a new version of the JAXP specification will probably support the new Level 3 scheme also.) Other parts of JAXP such as the javax.xml.transform portion do not have any other equivalent XSLT processor-independent APIs.
* Java Architecture for XML Binding (JAXB), v 1.0 and 2.0
Java Architecture for XML Binding (JAXB) provides an API and tool that allow automatic two-way mapping between XML documents and Java objects. With a given Document Type Definition (DTD) and a schema definition, the JAXB compiler can generate a set of Java classes that allow developers to build applications that can read, manipulate and recreate XML documents without writing any logic to process XML elements. The generated codes provide an abstraction layer by exposing a public interface that allows access to the XML data without any specific knowledge about the underlying data structure. In addition to DTD support, future versions of JAXB will add support for other schema languages, such as the W3C XML Schema. These features enable the JAXB to provide many benefits for the developers, which are further explained in the next section.
* JAX-RPC v 1.1
To aid developers in building XML-based requests such as SOAP requests, The JCP is developing the Java APIs for XML based RPC (JAX/RPC). JAX/RPC is used for sending and receiving (including marshalling and unmarshalling) method calls using XML-based protocols such as SOAP, or others such as XMLP (XML Protocol. For more information, see http://www.w3.org/2000/xp/). JAX/RPC isolates you from the specifics of these protocols, enabling rapid application development. There is no longer any need for developers to interact directly with the XML representation of the call.
* JAX-WS v 2.0
JAX-WS (Java API for XML Web Services) is a technology designed to simplify the construction of web services and web service clients in Java. The latest version, JAX-WS 2.0, which is part of the new Java EE 5 platform, provides powerful new tools and techniques to facilitate web service development.
* SAAJ (SOAP with Attachments API for Java)
SOAP with Attachments API for Java (SAAJ) is used mainly for the SOAP messaging that goes on behind the scenes in JAX-RPC and JAXR implementations. Secondarily, it is an API that developers can use when they choose to write SOAP messaging applications directly rather than use JAX-RPC. The SAAJ API allows you to do XML messaging from the Java platform: By simply making method calls using the SAAJ API, you can read and write SOAP-based XML messages, and you can optionally send and receive such messages over the Internet (some implementations may not support sending and receiving). This chapter will help you learn how to use the SAAJ API.
The SAAJ API conforms to the Simple Object Access Protocol (SOAP) 1.1 specification and the SOAP with Attachments specification. The SAAJ 1.2 specification defines the javax.xml.soap package, which contains the API for creating and populating a SOAP message.
* Java API for XML Registries (JAXR)
The Java API for XML Registries (JAXR) API provides a uniform and standard Java API for accessing different kinds of XML Registries. XML registries are an enabling infrastructure for building, deployment, and discovery of Web services.
An abstraction-based JAXR API gives developers the ability to write registry client programs that are portable across different target registries. This is consistent with the Java philosophy of Write Once, Run Anywhere. It also enables value-added capabilities beyond what the underlying registries are capable of. For example, a non-JAXR UDDI client does not have the ability to do taxonomy browsing and taxonomy-aware smart queries, which are available to a JAXR client for UDDI.
* Java API for XML Messaging (JAXM) - Optional
When receiving a web service request from say a business partner, we need a Java API to process XML messages, in a similar way to how we processed SOAP requests using JAX/RPC. The Java API for XML Messaging (JAXM) is a forthcoming specification for interacting with XML messaging standards such as ebXML messaging and SOAP messaging. This API is designed to facilitate the processing of XML message protocols, particularly those where a predetermined “contract” exists (ebXML in particular) to determine the format and constraints of the message. This API will handle all the “envelope” information, such as routing information and the “cargo” manifest, in an intuitive way separate from the actual payload of the message. This allows developers to focus on interacting with the payload and not worry about the other message administrivia.
Tuesday, March 3, 2009
Implementing AJAX using Java
AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script. Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript for dynamic content display. Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. Intuitive and natural user interaction. No clicking required only Mouse movement is a sufficient event trigger. Ajax is Data-driven as opposed to page-driven.
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script. Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript for dynamic content display. Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. Intuitive and natural user interaction. No clicking required only Mouse movement is a sufficient event trigger. Ajax is Data-driven as opposed to page-driven.AJAX is based on the following open standards:
* Browser-based presentation using HTML and Cascading Style Sheets (CSS)
* Data stored in XML format and fetched from the server
* Behind-the-scenes data fetches using XMLHttpRequest objects in the browser
* JavaScript to make everything happen
The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats.
You already have seen couple of examples on how to create a XMLHttpRequest object.
Below is listed some of the methods and properties you have to become familiar with.
XMLHttpRequest Methods
* abort() : Cancels the current request.
* getAllResponseHeaders() : Returns the complete set of HTTP headers as a string.
* getResponseHeader( headerName ) : Returns the value of the specified HTTP header.
* open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password ) : Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible
The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.
* send( content ) : Sends the request.
* setRequestHeader( label, value ) : Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties
* onreadystatechange : An event handler for an event that fires at every state change.
* readyState :
The readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is completed
readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
* responseText : Returns the response as a string.
* responseXML : Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
* status : Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
* statusText : Returns the status as a string (e.g. "Not Found" or "OK").
Steps of AJAX Operation
1. A client event occurs
A JavaScript function is called as the result of an event
2. An XMLHttpRequest object is created
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction(){
try{
xmlHttp = new XMLHttpRequest();
}catch (e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
return false;
}
}
}
}
3. The XMLHttpRequest object is configured
In this step we will write a function which will be triggered by the client event and a callback function processRequest() will be registered
function searchUser() {
// Here processRequest() is the callback function.
xmlHttp.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
4. The XMLHttpRequest object makes an asynchronous request to the Webserver.
ource code is available in the above piece of code. Code written in blue color is responsible to make a request to the web server. This is all being done using XMLHttpRequest object ajaxRequest
5. Webserver returns the result containing XML document.
You can implement your server side script in any language.
If we assume that you are going to write a servlet then here is the piece of code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim()))
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("true");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("false");
}
}
6. The XMLHttpRequest object calls the callback() function and processes the result.
The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will recieve the result from the server and will do required processing. As in the following example it sets a variable message on true or false based on retruned value from the Webserver.
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
7. The HTML DOM is updated
This is the final step and in this step your HTML page will be updated. It happens in the following way
* JavaScript technology gets a reference to any element in a page using DOM API
* The recommended way to gain a reference to an element is to call.
The Disadvantages of AJAX
1. Building an AJAX-powered application can increase development time and costs.
2. Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature.
3. Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications.
4. Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers.
5. AJAX is not meant to be used in every application. One of the main reasons for this stays in the fact that Google cannot index it.
6. The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object.
7. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.
Java JUnit
JUnit is an open source framework that has been designed for the purpose of writing and running tests in the Java programming language. JUnit was originally written by Erich Gamma and Kent Beck. There are many ways to write test cases. A test case is a code fragment that checks that another code unit (method) works as expected. So if we want an accurate and efficient testing process then using a good testing framework is recommended. JUnit has established a good reputation in this scenario.
JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems. Unit testing belongs to test a single unit of code, which can be a single class for Java. This framework creates a relationship between development and testing. You start coding according to the specification and need and use the JUnit test runners to verify how much it deviates from the intended goal. Typically, in a unit testing, we start testing after completing a module but JUnit helps us to code and test both during the development. So it sets more focus on testing the fundamental building blocks of a system i.e. one block at a time rather than module level functional testing. This really helps to develop test suites that can be run any time when you make any changes in your code. This all process will make you sure that the modifications in the code will not break your system without your knowledge.
JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily. JUnit shows test progress in a bar that is green if testing is going fine and it turns red when a test fails. There is a lot of pleasure in seeing the green bars grow in the GUI output. A list of unsuccessful tests appears at the bottom of the display window. We can run multiple tests concurrently. The simplicity of JUnit makes it possible for the software developer
to easily correct bugs as they are found.
JUnit Installation
1. First, download the latest version of JUnit from http://www.junit.org/ in zip format.
2. Then install JUnit on your platform of choice:
Windows
To install JUnit on Windows, follow these steps:
1. Unzip junit distribution file to a directory referred to as %JUNIT_HOME%.
2. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit-4.x.x.jar
Unix (bash)
To install JUnit on Unix, follow these steps:
1. Unzip junit distribution file to a directory referred to as $JUNIT_HOME.
2. Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit-4.x.x.jar
3. (Optional) Unzip the $JUNIT_HOME/src.jar file.
4. Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message.
If the tests don't pass, verify that junit.jar is in the CLASSPATH.
5. Finally, read the documentation.
Writing Tests
1. Create a class:
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class SimpleTest {
2. Write a test method (annotated with @Test) that asserts expected results on the object under test:
@Test
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
3. If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
}
4. Although writing a main() method to run the test is much less important with the advent of IDE runners, it's still possible:
public static void main(String args[]) {
org.junit.runner.JUnitCore.main("junitfaq.SimpleTest");
}
}
5. Run the test:
* To run the test from the console, type:
java org.junit.runner.JUnitCore SimpleTest
* To run the test with the test runner used in main(), type:
java SimpleTest
The passing test results in the following textual output:
Time: 0
OK (1 tests)
Run JUnit using Ant
1. Define any necessary Ant properties like source folder path, library folder path or class name etc.
2. Set up the CLASSPATH to be used by JUnit:
3. Define the Ant task for running JUnit:
4. Run the test:
ant test
JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems. Unit testing belongs to test a single unit of code, which can be a single class for Java. This framework creates a relationship between development and testing. You start coding according to the specification and need and use the JUnit test runners to verify how much it deviates from the intended goal. Typically, in a unit testing, we start testing after completing a module but JUnit helps us to code and test both during the development. So it sets more focus on testing the fundamental building blocks of a system i.e. one block at a time rather than module level functional testing. This really helps to develop test suites that can be run any time when you make any changes in your code. This all process will make you sure that the modifications in the code will not break your system without your knowledge.
JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily. JUnit shows test progress in a bar that is green if testing is going fine and it turns red when a test fails. There is a lot of pleasure in seeing the green bars grow in the GUI output. A list of unsuccessful tests appears at the bottom of the display window. We can run multiple tests concurrently. The simplicity of JUnit makes it possible for the software developer
to easily correct bugs as they are found.
JUnit Installation
1. First, download the latest version of JUnit from http://www.junit.org/ in zip format.
2. Then install JUnit on your platform of choice:
Windows
To install JUnit on Windows, follow these steps:
1. Unzip junit distribution file to a directory referred to as %JUNIT_HOME%.
2. Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit-4.x.x.jar
Unix (bash)
To install JUnit on Unix, follow these steps:
1. Unzip junit distribution file to a directory referred to as $JUNIT_HOME.
2. Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit-4.x.x.jar
3. (Optional) Unzip the $JUNIT_HOME/src.jar file.
4. Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an "OK" message.
If the tests don't pass, verify that junit.jar is in the CLASSPATH.
5. Finally, read the documentation.
Writing Tests
1. Create a class:
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
public class SimpleTest {
2. Write a test method (annotated with @Test) that asserts expected results on the object under test:
@Test
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
3. If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
}
4. Although writing a main() method to run the test is much less important with the advent of IDE runners, it's still possible:
public static void main(String args[]) {
org.junit.runner.JUnitCore.main("junitfaq.SimpleTest");
}
}
5. Run the test:
* To run the test from the console, type:
java org.junit.runner.JUnitCore SimpleTest
* To run the test with the test runner used in main(), type:
java SimpleTest
The passing test results in the following textual output:
Time: 0
OK (1 tests)
Run JUnit using Ant
1. Define any necessary Ant properties like source folder path, library folder path or class name etc.
2. Set up the CLASSPATH to be used by JUnit:
3. Define the Ant task for running JUnit:
4. Run the test:
ant test
Subscribe to:
Comments (Atom)