Generics in Java | How to write parametrized class and method in Java | java Generics interview Question answer

Before to going start how write  parametrized class and method in Java . i would like to give some important fact about generic

1. java generic has introduced with JDK 1.5 along with Autoboxing, varargs, ,Enum
2. Generics  provide compile-time type safety that allows programmers to catch invalid types at compile time.
3. Not only can Java generics be used in fields and methods, it can also be used in class definitions to produce parameterized classes.


How to write  parametrized class

1. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

2. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.

public class Member<T> {
 private T id;
 public Member(T id) {
   this.id = id;
 }
 public T getId() {
   return id;
 }
 public void setId(T id) {
   this.id = id;
 }
 public static void main(String[] args) {
   Member<String> mString = new Member<String>("id1");
   mString.setId("id2");
   System.out.printf("id after setting id: %s%n", mString.getId());
   //output:  id after setting id: id2
 
   Member<Integer> mInteger = new Member<Integer>(1);
   mInteger.setId(2);
   System.out.printf("id after setting id: %d%n", mInteger.getId());
   //output:  id after setting id: 2
 }


How to write parametrized method

 1.All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

    2. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type        name.

   3.  The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type        arguments.

   4.  A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char).

public class GenericMethodTest
{
   // generic method printArray                        
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements             
         for ( E element : inputArray ){       
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    }
}

Java Clone() concept | how clone work in java | java clone interivew question answer

First of all Java clone() method has given in Object class with below
protected Object clone() throws CloneNotSupportedException

with above definition some time in interview question you will found like
  • Why clone() method has given in Object class
  • What is the reason behind to make clone() method protected
  • What meaning of CloneNotSupportExeption
  • What is Shallow cloning and deep cloning

Definition
Clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Use of Cloneable interface
 
We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Java clone() concept


1. Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.  The assignment of one reference to another merely creates another reference to the same object.
2.  When you don't want to modify the method caller's (or original) object.
 Different analysis on same set of data in an Object. Rather than fetching the data again and again, populate object once and clone it for a new analysis.
 Games - walls, doors, cars graphics - clone the object, change the params.
3.For any class to able to be cloned .clone() - it MUST implement java.lang.Cloneable interface. Otherwise is .clone is used, it throws java.lang.CloneNotSupportedException at runtime.
  It is a marker interface - which simply tells JVM that the Object.clone() method can be called on the objects of this or sub classes.
4. Shallow Copy - see clone() method in below code
 This is a result of the default cloning functionality provided by the Object.clone()
 When this is used, it copies the primitives and the references. Only references are copied to new cloned Object. Actual referenced object remains as it. That means, the member references in original and cloned object - point to same object.
 
5.  Deep Copy - see deepClone() method in below code
 Copy the actual member objects along with primitives and member references.
 We need to override the clone() method in order to achieve it. But need to make sure that member Objects that we are trying to copy, should also implement Cloneable, only then then can be cloned.
 
 
public class Clones {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("AAA", 123, 100, 200);
System.out.println("Original");
System.out.println(p1.salary.basic);
Person p2 = (Person) p1.deepClone();
//p2.name = "BBB";
//p2.salary.basic = 2222;
System.out.println(p1.equals(p2));
System.out.println("Clone");
System.out.println(p2.salary.basic);
System.out.println("Original");
System.out.println(p1.salary.basic);
}
}
// cloneable class implements Cloneable
class Person implements Cloneable {
public String name = null;
public int id = 0;
public Salary salary = null;
public Person(String name, int id, int basicSal, int bonusSal) {
this.name = name;
this.id = id;
// using Object type member to test for cloning
Salary sal = new Salary();
sal.basic = basicSal;
sal.bonus = bonusSal;
this.salary = sal;
}
// shallow copying
protected Object clone() throws CloneNotSupportedException {
// This is default cloning provided by the Object.clone()
return super.clone();
}
// deep copying
protected Object deepClone() throws CloneNotSupportedException {
// The clone() method produces an Object, which must be recast to the proper type
Person p = (Person) super.clone();
// In deep cloning, we also clone the member objects, but for this to work - //member objects should be Cloneable
p.salary = (Salary) p.salary.clone();
return p;
}
}
// member object of Person class as Cloneable. If it was not, then deep cloning //would not have been possible
class Salary implements Cloneable {
public int basic = 0;
public int bonus = 0;
public int getSalary() {
return basic + bonus;
}
// implementing clone()
protected Salary clone() throws CloneNotSupportedException {
Salary s = (Salary) super.clone();
return s;
}
}
// Cloneables with final fields - not meant go together. No error, but when try //to change, it cribs.
// The only solution is to remove the final modifier from the field, giving up //the benefits the modifier conferred.

Java interview question related Session listner, web services in MNC software company

Below Few Java interview question asked at MNC software company

1. How can you count active sessions by using listeners in JAVA.

we can do it by using HttpSessionListener for that you can create a session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.
 
Code  example,
 we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.


package com.xyzws.web.utils;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}


To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into our /WEB-INF/web.xml file:

   <!-- Listeners -->  <listener>    <listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>  </listener>

For show in JSP
 the following JSP code shows the total active session:
 <%@ page import="com.xyzws.utils.MySessionCounter"%><html>...  Active Sessions : <%= MySessionCounter.getActiveSessions() %>...</html>

2) what is XML schema and it tags??
 
Definition
An XML Schema defines and describes certain types of XML data by using the XML Schema definition language (XSD). XML Schema elements (elements, attributes, types, and groups) are used to define the valid structure, valid data content, and relationships of certain types of XML data. XML Schemas can also provide default values for attributes, and elements.


XML Schema has contains below :

  • The first statement, <?xml version="1.0" encoding="utf-8"?>, specifies the version of XML in use.

  • The second statement consists of several parts:

The xs:schema declaration indicates that this is a schema and that the xs: prefix will be used before schema items.

The xmlns:xs="http://www.w3.org/2001/XMLSchema" declaration indicates that all tags in this schema should be interpreted according to the default namespace of the World Wide Web Consortium (W3C), which was created in 2001.

The targetnamespace declaration names this schema as XMLSchema1.xsd and indicates its default location, which will be in a default URI (universal resource identifier) on your development server called tempuri.org.

When you create a schema with the XML Designer, the version and namespace statements are automatically added for you. You might modify the contents of these two declarations in some cases. For example, if you want to use a tag prefix other than "XS," you would need to define the default namespace for that tag in addition to the XS tag prefix.

A complex type called "addressType" is defined that will contain five elements of various data types. Note that each of the elements it contains is a simple, named type.


Example

How to write XML schema of below requirments
The final element in the purchaseOrder, Item, contains a facet called maxOccurs. Facets set limits on the type of content a simple type can contain. maxOccurs is used to constrain how many times an element can occur in the documents created from this schema. By default, maxOccurs is equal to one. In this case, setting it to unbounded indicates that the Item element can reoccur as many times as needed.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="addressType">
   <xs:sequence>
      <xs:element name="street1" type="xs:string"/>
      <xs:element name="street2" type="xs:string"/>
      <xs:element name="city" type="xs:string"/>
      <xs:element name="state" type="xs:string"/>
      <xs:element name="zip" type="xs:integer"/>
   </xs:sequence>
</xs:complexType>

<xs:element name="purchaseOrder">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="shipTo" type="addressType" />
            <xs:element name="billTo" type="addressType" />
            <xs:element name="shipDate" type="xs:date" />
            <xs:element name="item" maxOccurs="unbounded"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:schema>

Java Serialization concept | Most asked Serialization Interview Questions and Answers in MNC software company

Java Serialization is very important topic in interview . in every java interview question in MNC software company i face java serialization topic . below list of question you should remember well before going to interview


1) What is the difference between Serializable and Externalizable interface in Java?
This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.io  package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that useJava Serialization mechanism to serialize this object.

3) What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . serialVersionUID is used for version control of object. you can specify serialVersionUIDin your class file also.  Consequence of not specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.



4) While serializing you want some of the members not to serialize? How do you achieve it?
this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during java serialization process.

5) What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class.


6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?

Java serialization process  only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process . once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializableinterface , there constructor will be executed.

7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since onlyJava Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.

8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interviewprogresses.

9) Which methods are used during Serialization and DeSerialization process in java?
This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type.

10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

11)What are the ways to speed up Object Serialization? How to improve Serialization performance?
The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.

  •     Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
  •     Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
  •     Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.

12) What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:

    Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database.
    Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations.
    JSON Data Transfer - is recently popular data transfer format. A lot of web services are being developed in JSON due to its small footprint and inherent integration with web browser due to JavaScript format.
    Use Externalizable interface and implement the readObject and writeObject methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.


13)What changes are compatible and incompatible to the mechanism of java Serialization?
This is one of a difficult tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:

  •     Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled.
  •     The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream.
  •     Changing a transient field to a non-transient field is compatible change since it is similar to adding a field.
  •     Changing a static field to a non-static field is compatible change since it is also similar to adding a field.

Some Simple Examples of incompatible changes are:

  •     Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream.
  •     Deleting a existing Serializable fields will cause a problem.
  •     Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field.
  •     Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field.
  •     Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field.
  •     Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream.

JSESSIONID concept | what is JSESSIONID working concept in J2EE web application | JSESSIONID interview Question

JSESSIONID is generated by server (which contains servlet container) used for session management for web application because we allready know that HTTP protocal is sataless.

Many applications require a series of requests from a client to be associated with one another.Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. 

Java EE (or Web) developer should know, while browsing on a server, it keeps trace of some data about the browsing session in a server-side HttpSession object. For example an ecommerce web application needs to store somewhere the information about the shopping cart of non registered users.
 How the server can associate the remote session data with the specific navigation session? This is done through a cookie (or via a GET parameter in the URL) that gives to the server the session ID value.

In Java EE applications, the cookie name to identify the sessions is JSESSIONID.



Condition where  JSESSIONID created

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session, but not create it if it doesn't exists, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code is in control when the session is created)

Sessions are per-context:


SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.
 
(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates new session if there is no session yet. This can be turned off by session='false' page directive, in which case session variable is not available on JSP page at all.

JSESSIONID and session management very popular J2EE interview question .Apart from What is JSESSIONID interviewer are also interested in below interview question
How do you avoid using jsessionid?

  • Is it possible to disable jsessionid in tomcat servlet?
  • Under what conditions is a JSESSIONID created?
  • how to refresh JSESSIONID cookie after login?
  • How to monitor HTTP request to check JSESSIONID ?

JMS tutorial | Configuration JMS in Weblogic Application Server

steps to configure a sample JMS server that supports JTA. Suppose a weblogic server or cluster has already been created. Let's call it SampleServer.

  •     Create a Non-XA DataSouce
  •     Create a persistent JDBCStore. Use the non-XA DataSource created above. Don't forget to assign the store a prefix name, say 'Example'. A table ExampleWLStore should be created in the database if the configuration will be successful. Target the JDBCStore to SampleServer.
  •     Create a JMS server. Use the JDBCStore created above. Target it to SampleServer
  •     Create a JMS module. Target it to SampleServer
  •     In the JMS module, create subdeployment. Target the subdeployment to the JMS server.
  •     Create a Queue and a Queue Connection Factory in the JMS module and associate them with the subdeployment. Assign a JNDI name to the queue and the factory. Notice that when creating the queue connection factory, the xa-connection-factory-enabled flag should be set to 'true'.


Notes. It may be necessary to create the queue and the subdeployment and to target it to a JMS server. But you do not have to do this for connection factory. In the webblogic10 sample application medrec, you can see from the admin console that three queues are configured. But there is no connection factory. But JMS won't work without a factory. So where is the factory? The medrec source code reveals the secret. It turns out that weblogic has two predefined factories that can be used. The JmsClientImpl.java in medrec defines the following:

private String connectionFactoryName = "weblogic.jms.XAConnectionFactory";

Then the code uses this name as the JNDI name to look up the connection factory. For more information, look at the weblogic document on it.

Junit tutorial | Best Practices to write JUnit test cases in Java | Junit interview question

Introduction to JUnit Test

Uses
A framework for unit test. Used mainly to test individual classes and methods.

JUnit Library
In maven pom.xml:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>

The scope is "test". So the junit.jar will not be packaged into the application for deployment.
Configure Maven for Running JUnit
In maven pom.xml:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!--<skipTests>true</skipTests>-->
<testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>

If skipTests is true, no unit tests will be run.
If testFailureIgnore is true, the tests will be run and the build maven will succeed even if some tests fail.
If testFailureIgnore is false, the tests will be run and build will fail if a test fails.

The test results will go to the directory:
project_base_directory\target\surefire-reports

Traditional JUnit Test
The test class must extend the JUnit class TestCase or its subclasses.

    Use setUp() to initialize resources.
    Use tearDown() to release resources
    Every test method must start with the lowercase "test".

The lifecycle of a TestCase
The lifecycle of a TestCase used by the JUnit framework is as follows:

    Execute setUp().
    Call a test-prefixed method.
    Execute tearDown().
    Repeat these steps for each test method. This will occur even if setUp() or tearDown() throws an exception

Notes:
If setUp() throws an Exception, the test method and tearDown() will not be executed.
If the test method fails and throws an error or exception, tearDown() will still be executed.

Utility Methods from Assert

    assertTrue(String message, boolean condition)
    assertFalse(String message, boolean condition)
    fail(String message)
    assertEquals(String message, Object expected, Object actual)
    assertEquals(String message, String expected, String actual)
    assertEquals(String message, double expected, double actual, double delta)
    assertEquals(String message, int expected, int actual)
    assertSame(String message, Object expected, Object actual)
    assertNotNull(String message, Object object)
    assertNull(String message, Object object)

See the class junit.framework.Assert for more methods.

A Sample Class for Testing

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Sound {
 private Map<String, String> voicemap = new HashMap<String, String>() {
  {
   put("bee", "buzz");
   put("cow", "moo");
   put("dog", "woof");
   put("cat", "meow");
   put("snake", "hiss");
   put("bird", "chir");
   put("goose", "honk");
  }
 };

 public String speak(String animal) throws Exception {
  if (animal == null) {
   throw new Exception("animial is not specified.");
  }
  String name = animal.toLowerCase();
  Set<String> animals = voicemap.keySet();
  if (!animals.contains(name)) {
   throw new Exception("not implemented yet for this animal.");
  }
  return voicemap.get(name);
 }

 public String yell(String animal) throws Exception {
  String sound = speak(animal);
  return sound.toUpperCase();
 }
}


A Sample JUnit Test Class

import junit.framework.TestCase;

public class SoundTest extends TestCase {

/* This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the setUp() method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 @Override
 protected void setUp() throws Exception {
  super.setUp();
  sound = new Sound(); 
 }

 @Override
 protected void tearDown() throws Exception {
  sound = null;
  super.tearDown();
 }

 public void testSpeak() throws Exception {
  String beeSound = sound.speak("bee");
  assertEquals("buzz", beeSound);
  try {
   String temp = sound.speak("fish");
   fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   assertEquals("The sound of goose is not right", "HONK", gooseYell);
  } catch (Exception e) {
   fail("Test failed. This statement should not have been reached.");
  }
 }
}


Run JUnit in Eclipse


Run JUnit Test On CommandLine
JUnit provides the TestRunner classes for running all the tests. The two most popular test runners are a text-based one, junit.textui.TestRunner, and a Swing-based one, junit.swingui.TestRunner

Example:
java junit.textui.TestRunner org.example.SampleTest

TestSuite
JUnit tests can be grouped together by using the TestSuite class.
Example:

import junit.framework.Test;
import junit.framework.TestSuite;

public class GroupTests extends TestSuite {
      static public Test suite() {
            TestSuite suite = new TestSuite();
             suite.addTestSuite(SimpleTest1.class);
             suite.addTestSuite(SimpleTest2.class);
             return suite;
    }
}


When this test is run, both SimpleTest1 and SimpleTest2 will be invoked.

Junit Test Using Annotation in JUnit4

    No need to extend the class TestCase
    No need to use setUp() or tearDown(). Use @Before and @After instead.
    The test method name does not need to start with "test". But you need to put the @Test annotation before each test method.
    Use @Test(expected = YourException.class) to test exception
    Can use @Test(timeout = ?) for performance testing. Here "?" is time in milliseconds.
    Can use @Ignore to ignore a test

Example Using Annotation

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class SoundAnnotationTest {

/** This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the @Before method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 /**
  * The method name does not have to be setUp. You can have multiple such
  * methods with the "Before" annotattion, each of which is run before each
  * test
  */
 @Before
 public void setUp() {
  sound = new Sound();
 }

 /**
  * The method name does not have to be tearDown. You can have multiple such
  * methods with teh "After" annotation, each of which is run after each
  * test.
  */
 @After
 public void tearDown() {
  sound = null;

 }

 @Test
 public void speak() {
  try {
   String beeSound = sound.speak("bee");
   Assert.assertEquals("buzz", beeSound);
  } catch (Exception e) {
   Assert.fail("Test failed.");
  }

  try {
   sound.speak("fish");
   Assert.fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 @Test
 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   Assert.assertEquals("The sound of goose is not right", "HONK",
     gooseYell);
  } catch (Exception e) {
   Assert.fail("Test failed. This statement should not have been reached.");
  }
 }

 @Test(expected = Exception.class)
 // IndexOutOfBoundsException.class
 public void testFish() throws Exception {
  sound.speak("fish");
 }

 @Test(timeout = 700)
 public void testPerformance() throws Exception {
  Thread.currentThread().sleep(600);
 }

 @Ignore
 public void foo() throws Exception {
  for (int i = 0; i < 10; i++) {
   // no-op
  }
 }
}


Use EasyMock in JUnit

    Create Mock object using EasyMock.createMock
    Mock expected results using EasyMock's expect and the andReturn()/andThrow() method
    You can use andReturn to return the value you want.
    You can use andThrow to throw any kind of exception you like.
    Call the EasyMock replay() method.
    Do test and check results.


Example Using EasyMock

(MyServiceEndpointTest)
fooServiceMock = createMock(FooService.class);
barServiceMock = createMock(BarService.class);
endPoint = new MarshallingCommonServiceEndpoint(barServiceMock,
    fooServiceMock);
expect(barServiceMock.getSomeInput(arg1, arg2)).andReturn(Boolean.TRUE);
replay(barServiceMock);
GetBarResponse response = endPoint.getBar(request);
assertTrue("Invalid status", response.isStatus());