Saturday, March 31, 2012

Enums demystified

Why enums came into picture?

Before enums came into picture we all were using constants for different values.
There would be a constant file in which we define values like this

public static final int LOW=1;
public static final int MEDIUM=2;
public static final int HIGH=3;

Above approach works,but there are following issues.These are:-
i)Programmer is not bounded to use the constants.Programmer can put any int value and code will work fine.
ii)LOW/MEDIUM/HIGH are just variable names. So when we print LOW/MEDIUM/HIGH it prints 1/2/3 which does not convey any meaning.

So java introduced enums.Enum is like a class or interface which is used to define a set of constants.Enum constants can't be changed once created and we are free to add behavior to it by adding abstract methods and interfaces.It provides type safety and can be used inside a switch statement.Moreover they are initialized when enum class is loaded.



Plain enums

Plain enum are constants without any parametrized value.In the current example-GenderEnum we are having two constants M,F for male and female gender respectively.

package com.kunaal.enumDetails;

/**
 * @author KunaalATrehan
 *
 */
public enum GenderEnum {
 M,F;
}


Parametrized enums



Plain enum do provide type safety.However to provide more meaningful implementation we have to use overloaded constructor of the enum.

Lets take the example of Income group enum.Here by using parametrized enum we are able to convey the meaning of enum constant more effectively.

package com.kunaal.enumDetails;

/**
 * @author KunaalATrehan
 *
 */
public enum IncomeGroupEnum {
 BPL("Below Poverty Line"),
 LIG("Lower Income Group"),
 MIG("Middle Income Group"),
 HIG("High Income Group");
 
 //Variable for data val
 private String dataVal;

 /**
  * @return the dataVal
  */
 public String getDataVal() {
  return dataVal;
 }

 /**
  * Parameterized constructor
  * @param dataVal
  */
 private IncomeGroupEnum(String dataVal) {
  this.dataVal = dataVal;
 }

}








Are enums similar to normal java classes?

Enums are exactly like java classes.Enums can implement an interface and can have abstract methods.In order to understand it better,lets take an example.

Here we are creating an enum for educational qualifications.This enum has an abstract method called print(). This abstract print() method is overridden by each enum value.

package com.kunaal.enumDetails;

/**
 * @author KunaalATrehan
 *
 */
public enum EducationDtlEnum {
  PG("Post Graduate") {
   @Override
   public void print() {
    System.out.println("Person may have done MBA,MCA,MS or similar things");
   }
  },
  UG("Under Graduate") {
   @Override
   public void print() {
    System.out.println("Person may have done Diploma. ");
   }
  },
  GRAD("Graduate") {
   @Override
   public void print() {
    System.out.println("Person may have done BE,BTech,BSC,BBA or similar things");
   }
  },
  HS("High School") {
   @Override
   public void print() {
    System.out.println("Person has finished the high school");
   }
  },
  PHD("Doctorate") {
   @Override
   public void print() {
    System.out.println("Person may have doen PHD,MD or similar things.");
   }
  };
  
  //Variable for dataval
  private String dataVal;
  
  /**
   * Parameterized constructor
   * @param value
   */
  private EducationDtlEnum(String value){
   this.dataVal=value;
  }

  /**
   * @return the dataVal
   */
  public String getDataVal() {
   return dataVal;
  }
  
  //Abstract print method
  public abstract void print();
}


Enum example using plain,parametrized and enums with abstract method

Person class containing following variables
-String variable for name
-Plain enum 'GenderEnum' for capturing person's gender
-Parametrized enum 'IncomeGroupEnum' for capturing person's income group
-Parametrized enum 'EducationDtlEnum' with abstract method print()

package com.kunaal.enumDetails;

/**
 * @author KunaalATrehan
 *
 */
public class Person {
 
 //Enum for education details
 private EducationDtlEnum educationInfo;
 
 //Enum for income group
 private IncomeGroupEnum incomeGroup;
 
 //Variable for name
 private String name;
 
 //Variable for gender
 private GenderEnum genderEnum;

 /**
  * @return the genderEnum
  */
 public GenderEnum getGenderEnum() {
  return genderEnum;
 }

 /**
  * @param genderEnum the genderEnum to set
  */
 public void setGenderEnum(GenderEnum genderEnum) {
  this.genderEnum = genderEnum;
 }

 /**
  * @return the educationInfo
  */
 public EducationDtlEnum getEducationInfo() {
  return educationInfo;
 }

 /**
  * @param educationInfo the educationInfo to set
  */
 public void setEducationInfo(EducationDtlEnum educationInfo) {
  this.educationInfo = educationInfo;
 }

 /**
  * @return the incomeGroup
  */
 public IncomeGroupEnum getIncomeGroup() {
  return incomeGroup;
 }

 /**
  * @param incomeGroup the incomeGroup to set
  */
 public void setIncomeGroup(IncomeGroupEnum incomeGroup) {
  this.incomeGroup = incomeGroup;
 }

 /**
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }
 
 /**
  * Overridden toString() method
  */
 @Override
 public String toString() {
  return "Person [educationInfo=" + educationInfo + ", genderEnum="
    + genderEnum + ", incomeGroup=" + incomeGroup + ", name="
    + name + "]";
 }
}

Enum example making different concrete implementation of Person class.
This example contains different methods to test different functionalities provided by enum.
i.e
-printValues() prints enumeration value.
-refCheck(..) checks for == implementation.
-abstractEnumMthdImpl(...) invokes overridden abstract method in different enums.
-defaultToString(..) invokes toString() method of the enum
-equalityChk(..) checks for equals implementation.

package com.kunaal.enumDetails;

/**
 * @author KunaalATrehan
 *
 */
public class EnumExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Person person=new Person();
  person.setName("Mr. A");
  person.setEducationInfo(EducationDtlEnum.PHD);
  person.setIncomeGroup(IncomeGroupEnum.HIG);
  person.setGenderEnum(GenderEnum.M);
  
  Person person2=new Person();
  person2.setName("Mrs. B");
  person2.setEducationInfo(EducationDtlEnum.PHD);
  person2.setIncomeGroup(IncomeGroupEnum.HIG);
  person2.setGenderEnum(GenderEnum.F);
  
  Person person3=new Person();
  person3.setName("Mr. C");
  person3.setEducationInfo(EducationDtlEnum.PG);
  person3.setIncomeGroup(IncomeGroupEnum.MIG);
  person3.setGenderEnum(GenderEnum.M);
  
  //print enum data 
  printValues();
  
  //chk for references
  refCheck(person, person2, person3);
  
  //testing interface mthd  implementation
  abstractEnumMthdImpl(person, person2, person3);
  
  //testing default toString method
  defaultToString(person,person2,person3);
  
  //testing equals method
  equalityChk(person,person2,person3);
  
  //invoke toString() on person objects
  System.out.println(person);
  System.out.println(person2);
  System.out.println(person3);
 }
 
 /**
  * This method print values of the enumeration 
  */
 private static void printValues(){
  System.out.println("----Enumeration values-------");
  
  for(EducationDtlEnum data:EducationDtlEnum.values()){
   System.out.println(data);
  }
  System.out.println("---------------------------------------");
 }
 
 /**
  * This method checks whether enum objects are created once 
  * or created for every reference.
  * 
  * @param person
  * @param person2
  * @param person3
  */
 private static void refCheck(Person person,Person person2,Person person3){
  System.out.println("Checking for reference ==");
  System.out.println("---------------------------------------");
  System.out.println(person.getEducationInfo()==(person2.getEducationInfo()));
  System.out.println(person.getEducationInfo()==(person3.getEducationInfo()));
  System.out.println("---------------------------------------");  
 }
 
 /**
  * Here our custom enum has an abstract method print whose implementations are provided
  * by all the enums.We are invoking that method.
  * 
  * @param person
  * @param person2
  * @param person3
  */
 private static void abstractEnumMthdImpl(Person person,Person person2,Person person3){
  System.out.println("Get print implementations");
  System.out.println("------------------------------------");
  person.getEducationInfo().print();
  person2.getEducationInfo().print();
  person3.getEducationInfo().print();
  System.out.println("------------------------------------");  
 }
 
 /**
  * This method invokes the default toString() method of enum
  * 
  * @param person
  * @param person2
  * @param person3
  */
 private static void defaultToString(Person person,Person person2,Person person3){
  System.out.println("Get toString() implementations");
  System.out.println("---------------------------------------");
  System.out.println(person.getEducationInfo().toString());
  System.out.println(person2.getEducationInfo().toString());
  System.out.println(person3.getEducationInfo().toString());
  System.out.println("---------------------------------------");
  
 }
 
 /**
  * This method invokes the default equals method of enum
  * 
  * @param person
  * @param person2
  * @param person3
  */
 private static void equalityChk(Person person,Person person2,Person person3){
  System.out.println("Equality check");
  System.out.println("---------------------------------------");
  System.out.println(person.getEducationInfo().equals(person2.getEducationInfo()));
  System.out.println(person.getEducationInfo().equals(person3.getEducationInfo()));
  System.out.println("---------------------------------------");
  
  
 }

}

Output of the above code

----Enumeration values-------
PG
UG
GRAD
HS
PHD
---------------------------------------
Checking for reference ==
---------------------------------------
true
false
---------------------------------------
Get print implementations
------------------------------------
Person may have doen PHD,MD or similar things.
Person may have doen PHD,MD or similar things.
Person may have done MBA,MCA,MS or similar things
------------------------------------
Get toString() implementations
---------------------------------------
PHD
PHD
PG
---------------------------------------
Equality check
---------------------------------------
true
false
---------------------------------------
Person [educationInfo=PHD, genderEnum=M, incomeGroup=HIG, name=Mr. A]
Person [educationInfo=PHD, genderEnum=F, incomeGroup=HIG, name=Mrs. B]
Person [educationInfo=PG, genderEnum=M, incomeGroup=MIG, name=Mr. C]

Thursday, December 1, 2011

Singleton and serialization

What is singleton?

In Java ,we can create objects by calling constructor.But imagine a scenario where we want to 
control object instantiation.There could be many reasons why we want to control the object creation.
Normally in 3 tier architecture we create single instance of service and DAO objects since we don't want to create multiple DAO objects as number of database connections are limited and by creating multiple DAO objectswe donot want to exhaust database connections.
This is just one example ,there could be multiple such examples in real world.

Code snippet for a singleton class

Here I am using double check mechanism for creating a singleton instance.

package com.kunaal.algo;

import java.io.Serializable;

/**
 * Here we are making ConnectionFactory as a singleton.
 * Since we want connection factory to be initiated once and used
 * by different classes of the project.
 * 
 * We also want to read the connection parameters once and use it as
 * a place holder for pooled connections.
 * 
 * @author KunaalATrehan
 *
 */
public class ConnectionFactory implements Serializable{
 //Static variable for holding singleton reference object
 private static ConnectionFactory INSTANCE;
 
 /**
  * Private constructor
  */
 private ConnectionFactory(){  
 }
 
 /**
  * Static method for fetching the instance
  * @return
  */
 public static ConnectionFactory getInstance(){
  //Check whether instance is null or not
  if(INSTANCE ==null){
   //Locking the class object
   synchronized(ConnectionFactory.class){
    //Doing double check for the instance
    //This is required in case first time two threads simultaneously invoke 
    //getInstance().So when another thread get the lock,it should not create the 
    //object again as its already created by the previous thread.
    if(INSTANCE==null)
     INSTANCE=new ConnectionFactory();
   }   
  }
  
  return INSTANCE;
 }
}

What happens when we serialize the singleton?

Serialization allows storing the object in some data store and re create it later on.However when we serialize a singleton class and invoke deserialization multiple times.We can end up with multiple objects of the singleton class.Even though constructor is private,deserialization process gets hold of the private constructor while recreating the object from the serialized data store.

So can we avoid it.Yes we can avoid it.We will go through step by step and explain what needs to be done when we reconstruct the object from the serialized data store so that singleton behavior is not broken when object reconstruction happens.

Case-1: Serialization breaking singleton behavior

Here we are serializing the singleton instance and reading it multiple times.So we will see that INSTANCE reference is same,however multiple objects are created.


package com.kunaal.algo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author KunaalATrehan
 *
 */
public class SerializationTest {

 /**
  * @param args
  * @throws IOException 
  * @throws FileNotFoundException 
  * @throws ClassNotFoundException 
  */
 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
  ConnectionFactory INSTANCE=ConnectionFactory.getInstance();
  
  //Here I am serializing the connection factory instance
  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("connFactory.ser"));  
        oos.writeObject(INSTANCE);  
        oos.close();  
        
        //Here I am recreating the instance by reading the serialized object data store
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("connFactory.ser"));  
        ConnectionFactory factory1 = (ConnectionFactory) ois.readObject();  
        ois.close();  
        
        //I am recreating the instance AGAIN by reading the serialized object data store
        ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("connFactory.ser"));  
        ConnectionFactory factory2 = (ConnectionFactory) ois2.readObject();  
        ois2.close();
        
        //Lets see how we have broken the singleton behavior
        
        System.out.println("Instance reference check->" +factory1.getInstance());
        System.out.println("Instance reference check->" +factory2.getInstance());
        System.out.println("=========================================================");
        System.out.println("Object reference check->"+factory1);
        System.out.println("Object reference check->"+factory2);
 }

}

Output is as follows:-


Instance reference check->com.kunaal.algo.ConnectionFactory@763f5d
Instance reference check->com.kunaal.algo.ConnectionFactory@763f5d
=========================================================
Object reference check->com.kunaal.algo.ConnectionFactory@13a317a
Object reference check->com.kunaal.algo.ConnectionFactory@186768e

So it has created two objects and one static reference for INSTANCE.So that means if we read the serialized format of singleton object multiple times,we will create multiple objects.This is not what singleton object is supposed to do.So can we avoid it,Yes we can.We will discuss the same in the next use case.

Case-2: Serialization and singleton working properly

In order to make serialization and singleton work properly,we have to introduce readResolve() method in the singleton class.readResolve() method lets developer control what object should be returned  on deserialization.
For the current ConnectionFactory singleton class,readResolve() method will look like this.
       /**
  * Special hook provided by serialization where developer can control what object needs to sent.
  * However this method is invoked on the new object instance created by de serialization process.
  * @return
  * @throws ObjectStreamException
  */
 private Object readResolve() throws ObjectStreamException{
  return INSTANCE;
 }

Output  is as follows:-

Instance reference check->com.kunaal.algo.ConnectionFactory@13a317a
Instance reference check->com.kunaal.algo.ConnectionFactory@13a317a
=========================================================
Object reference check->com.kunaal.algo.ConnectionFactory@13a317a
Object reference check->com.kunaal.algo.ConnectionFactory@13a317a

So now serialization and singleton is working properly and it does not matter how many times we read the serialized format of singleton object.We will get the one instance.readResolve() did the trick

Friday, November 18, 2011

Maven basics

Birth of maven

Before ANT came into place,developers used to compile java classes through command line  and generate the corresponding jar/war.It was error prone and lengthy process.


Then ANT came into picture.Developers used to write build script and use ANT to generate the required artifacts.However developer still need to write or customize the build script.Every project had a different structure ,roughly same build process with files spread over directories spread over source code.Different targets were created for cleaning the build directories,compiling the source code,running the test script,creating the deployment artifacts like war,ear,jar ,....
Developer used to worry about the dependent libraries and other stuff.



Then MAVEN was born.It standardized the project structure for most types of projects.Automated common activities like clean,compile,package and others.Relieved developers of fixing the dependencies of direct or indirect libraries.It removed inconsistent setup across developers and made process simple and transparent.

What all maven do?


Maven is a build and project management tool.

It is a build tool because of following reasons.These are:-
i) It has normalized and standardized the project structure

ii) Dependencies of third party libraries are handled gracefully.Developer need not have to download the jars and push it in the class path for building.Developer defines that this project is dependent on these tools/libraries in the pom.xml and maven does the magic of downloading  the associated jars,building the class path and managing the versions for different dependencies.

iii)We can generate the required artifacts from the project like war,jar,...Since maven has standardized the project structure.It knows which files needs to be compiled,how properties and other configuration files needs to packaged and generate the project artifact.Developer has to just fire the required goal.

iv)Lets suppose you are working in distributed environment where changes made in one module affects other module.So using mvn package will deploy the application in local /shared repository  from where others can define it as a dependency and latest changed jar file will be available to others.

v) Using various plugins we can do lots of other activities eg.plugin for jetty helps you run the war file and others.

It is a project management tool because of following reasons.These are:-
i) We can integrate integration tool like cruise control and other such tools with maven.So when any code is committed,cruise control process will run.

ii) We can integrate Bugzilla with maven.

iii)We can generate java docs,unit test reports,code coverage,code analysis using mvn site.The project site generation goal creates a professional web site of your project, including links to syntax highlighted source code, code metrics, javadoc, unit test results, and more.

Foundation blocks of maven

Maven consists of two repositories.These are :-


i) Archetype repository
Archetype repository contains information about different project types.When we invoke mvn archetype:generate.It list down the projects that we want to create.
Depending upon the selection maven creates the standardized directory structure containing folders for configuration files,source code,test cases and other required setup.

ii) Dependency repository
Most of the project depends upon third party libraries and these libraries depends upon other libraries.Different versions have different version dependencies.Maven helps in dependency management.By defining dependency of the project on third party library and corresponding version ,maven will automatically download the mentioned dependency and all other libraries which this version of dependency require.

These two are foundation blocks of the maven.

Archetype,ArtifactId,GroupId and Version

Lets take the example of creating a web based  application in java.
A web based application  needs WEB-INF,web.xml ,source folder ,test cases folder.

So what needs to be done and how maven assists us in making such application.Lets go through step by step .
1. After installing maven ,go to the directory where you want project to be setup.
Lets say we created a folder named 'DummyWebApp' under C: drive.

2. Go to C:\DummyWebApp.

3.Type mvn  archetype:generate

4.It will show you the list of project types present in maven archetype repository.So archetype is nothing but a standardized template of a project with some defaults.

5.For web based application we will enter 1 when prompt for 'Chose a number or apply filter' comes.

6.Then it  will prompt for 'Choose version:' i.e which version of archetype template you want to choose.It would have shown you the different versions available for the archetype you have selected.Go ahead with the default one.

7.Then it will prompt for ' Define a value for property <groupId>'.groupId refers to the structure in which you want to package your project in local repository or remote repository.
Eg. 
Lets suppose your code jar file is required by other dependent projects.So if you construct your jar file as ABC.jar and define groupId as com.kunaal.deploy.Then if you invoke mvn install.It will put ABC.jar inside com\kunaal\deploy folder of your local repository.

8.Then it will prompt for 'Define a value for property <artifactId>'.ArtifactId refers to name of your packaged file i.e name of the jar or war file which your project will create.
Eg.
If we give artifactId as 'Kunaal' so when we do mvn package and project is web based application and packaging strategy is 'war'.It will create Kunaal.war.

9.Then it will prompt for 'Define a value for property <version>'.Define a version

10.Then it will prompt for 'Define a value for property <package>'.i.e how you want the package structure.Normally groupId and package property is kept same.
Now you are done.It will create a directory structure like this 
DummyWebApp
                      -------> pom.xml
                      -------->src
                                           --->main
                                                         -----> java
                                                         -----> test
                                                        ------> webapp
                                                                              ------> WEB-INF ---->web.xml
                                                                              ------> index.jsp
                                                         ------> resources

So you can see by simply following the instructions.We can create a standardized project with defaults .



What is dependency and how to inform maven about it?

Every project need some third party libraries.These libraries acts as a dependency in maven.Some dependencies are required for running test cases, some are required for compiling,some are standardized service level interfaces whose implementation is provided by the server like servlet api and others.So in order to define these dependencies in pom.xml .We add a dependency tag .

Lets take an example.
Our application is dependent upon log4j and Junit.We need log4j for logging.So instead of downloading the same and publishing it in classpath.We will add dependency for the same in pom.xml.

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency>
 
So in our repository there would be folder named <groupId>\<artifactId>\<version>
Inside this there would be pom file for the same and corresponding library file.In this case there would be a folder like ...\.m2\log4j\log4j\1.2.16\log4j.jar

Similarly for JUnit,dependency would be like this.
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.7</version>
      <scope>test</scope>
</dependency>

There is one difference here.Scope of junit dependency is 'test'.By default scope of dependency is 'compile'.Following scopes are available for dependencies.These are:-

i)Compile-This is the default scope.It means that these libraries are available at the compile time.These libraries are available in classpath of the project.

ii)Test-This means that these libraries are available during compilation and execution of test cases.

iii)Provided-This means that these libraries are provided by the container or the jdk.eg servlet

iv)Runtime-This means that these libraries are available at the runtime.

Common goals of maven
Following are the common goals of the maven.These are :-
i) validate - This checks whether project structure is proper or not and all necessary information is available or not.

ii) compile - This compiles the source code

iii)test - This runs the test cases

iv)package - This takes the compiled code and distribute it in the suitable format like jar,war

v)install -This installs the package in the local repository so that other local projects can use it.

vi) deploy- This copies the package in the remote repository.Normally done during release phase of the project.

When we invoke any goal through maven,all previous goals in the hierarchy will also run.
eg. We invoke mvn install
It will run validate,compile,test,package and install.


Settings.xml

Maven execution settings are defined in settings.xml.It contains information about the local repository,whether maven should interact with user for their input or not,whether it should work in offline mode or not.

It also states the information regarding repositories,servers and other profile related information.This file is available at following two places.These are:-
  • The Maven install: $M2_HOME/conf/settings.xml
  • A user's install: ${user.home}/.m2/settings.xml
 First one is called Global setting.Second one is called user settings.If both are present then these gets merged with user settings taking the major role.




Wednesday, September 28, 2011

Information about Mock and Stub

One of the common questions in interview,have you written test cases for your Java Code.If your code uses some other class,how you resolved this dependency.
Have you used Stubs or Mocks and whats the reason behind it?
Is there any difference between them?

Lets discuss this scenario and figure out when to use what.
Use Case
We have to create authentication module in our system.It checks for username and password and returns true or false depending upon whether username and password supplied is correct
or not.In our use case we have a LoginService which uses IUserDAO.There is a concrete class named UserDAO which implements IUserDAO and uses database table for doing authentication check.It will return success/failure as authentication result

So now if we have to write test case for LoginService authenticate () method.We need to provide some implementation for IUserDAO for test case to complete.We fake the IUserDAO  implementation by creating a mock or stub of it.

What is Stub?

Stub is a fake implementation of the dependent class.If we follow interface driven approach we can create a stub by implementing the interface and provide hard coded return values.
The basic idea is to implement the dependencies as concrete classes, which reveal only a small part of the overall behavior of the dependent class, which is needed by the class under test.

+ves
-There is no dependency on external jars.
-We are writing extra class having redundant implementation and hard coded return values for testing our api.
-Easy to simulate and understand

-ves
-If interface changes we have to modify the stubs.
-There could be multiple stub implementations for testing different  api's because if we use one stub class for all test case,we may break other test cases.
-If interface has many methods our stub will have lots of empty methods.

Above use case with Stub Implementation

 
package com.kunaal.stubMock.test;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.kunaal.stubMock.dao.IUserDAO;
import com.kunaal.stubMock.service.LoginService;

/**
 * @author Kunaal A Trehan
 *
 */
public class LoginServiceTest {
	
	private LoginService loginService=new LoginService();
	
	/**
	 * Here we setting stub implementation for userDAO which we will use in this service
	 * So interface driven approach helps us to fake the dependency by injecting  
	 * stub[anonymous implementation of IUserDAO] of other class and let us test 
	 * our method  
	 */
	@Before
	public void stubSetup(){
		loginService.setUserDAO(new IUserDAO(){

			public boolean authenticate(String uName, String passWd) {
				if(uName!=null && uName.equals("Kunaal") && 
						passWd !=null && passWd.equals("Password"))
					return true;
				else
					return false;
			}
		});
	}
	
	
	@Test
	public void authenticate(){
		assertTrue(loginService.authenticate("Kunaal", "Password"));
		assertFalse(loginService.authenticate("Kunaal", "Kunaal"));
	}

}


What is Mock?


Mock also fake's the implementation .But in case of mock we record and verify the interaction between the two classes.Basic idea is to plug the expectation at the runtime and verify the same.

+ves

-No need to create an extra class for faking the implementation
-Relives us from having blank implementations for methods in case number of methods are huge.
-We can define the expectation at the run time
-We can verify whether the method in the dependent class has actually been invoked or not

-ves
-Need third party api for providing mocking behavior
-Its not straight forward to understand

Above use case with mock implementation

package com.kunaal.stubMock.test;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import com.kunaal.stubMock.dao.UserDAO;
import com.kunaal.stubMock.service.LoginService;

/**
 * @author Kunaal A Trehan
 *
 */
public class MockLoginServiceTest {
	
	private LoginService loginService;
	private UserDAO mockUserDAO;
	
	@Before
	public void setup(){
		loginService=new LoginService();
		mockUserDAO=createMock(UserDAO.class);
		loginService.setUserDAO(mockUserDAO);
	}
	
	@Test
	public void authenticate(){
		//push the expectations and other information
		// Set expectations on mocks.
		expect(mockUserDAO.authenticate("Kunaal","Password")).
			andReturn(true);
		// Set mocks into testing mode.
		replay(mockUserDAO);
		
		assertTrue(loginService.authenticate("Kunaal", "Password"));
		//assertFalse(loginService.authenticate("Kunaal", "Kunaal"));
		verify(mockUserDAO);
	}


}

Whats the difference between these two?
So final word whats the difference between these two.As per my understanding mock is generated at the run time and it helps to test the state as well as interaction behavior between two classes.This is not possible in stub implementation as there is no way to verify whether the particular method in the dependent class has been invoked by the test class or not.


However I can be wrong.Do let me know if my understanding is not right.