Monday, January 16, 2017

Hibernate - Overview

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.

Hibernate - Architecture

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.

Hibernate - Environment

This chapter will explain how to install Hibernate and other associated packages to prepare a develop environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate examples, so make sure you already have setup for MySQL database. For a more detail on MySQL you can check our MySQL Tutorial.

Hibernate - Configuration

Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters.

Hibernate - Sessions

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

Hibernate - Persistent Class

The entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields.

Hibernate - Mapping Files

An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate how to map the defined class or classes to the database tables.

Hibernate - Mapping Types

When you prepare a Hibernate mapping document, we have seen that you map Java data types into RDBMS data types. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, which can translate from Java to SQL data types and vice versa.

Hibernate - Examples

Let us try an example of using Hibernate to provide Java persistence in a standalone application. We will go through different steps involved in creating Java Application using Hibernate technology.

Hibernate - O/R Mappings

So far we have seen very basic O/R mapping using hibernate but there are three most important mapping topics which we have to learn in detail. These are the mapping of collections, the mapping of associations between entity classes and Component Mappings.

Hibernate - Annotations

So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations is the newest way to define mappings without a use of XML file.

Hibernate - Query Language

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Hibernate - Criteria Queries

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

Hibernate - Native SQL

You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Hibernate - Caching

Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications.

Hibernate - Batch Processing

Consider a situation when you need to upload a large number of records into your database using Hibernate. Following is the code snippet to achieve this using Hibernate:
Session session = SessionFactory.openSession();

Hibernate - Interceptors

As you have learnt that in Hibernate, an object will be created and persisted. Once the object has been changed, it must be saved back to the database. This process continues until the next time the object is needed, and it will be loaded from the persistent store.

Discuss Hibernate

Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps.


Hibernate - Useful Resources

The following resources contain additional information on Hibernate. Please use them to get more in-depth knowledge on this topic.

Hibernate Questions and Answers

Hibernate Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

Guava - Overview

Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates the best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.

Guava - Environment Setup

Try it Option Online

We have setup a Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

Guava - Optional Class

Optional is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values.

Guava - Preconditions Class

Preconditions provide static methods to check that a method or a constructor is invoked with proper parameter or not. It checks the pre-conditions. Its methods throw IllegalArgumentException on failure.

Guava - Ordering Class

Ordering can be seen as an enriched comparator with enhanced chaining functionality, multiple utility methods, multi-type sorting capability, etc.

Guava - Objects Class

Objects class provides helper functions applicable to all objects such as equals, hashCode, etc.
Class Declaration

Guava - Range Class

Range represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range.

Guava - Throwables Class

Throwables class provides utility methods related to Throwable interface.

Class Declaration

Guava - Collections Utilities

Guava introduces many advanced collections based on developers' experience in application development works. Given below is a list of useful collections:

Guava - Caching Utilities

Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs.

Guava - String Utilities

Guava introduces many advanced string utilities based on developers' experience in application development works. Following is the list of useful string based utilities:

Guava - Primitive Utilities

As primitive types of Java cannot be used to pass in generics or in collections as input, Guava provided a lot of Wrapper Utilities classes to handle primitive types as Objects. Following is the list of useful primitive processing utilities:

Guava - Math Utilities

Guava provides Mathematics related Utilities classes to handle int, long and BigInteger. Following is the list of useful utilities:

Guava - Useful Resources

The following resources contain additional information on Guava. Please use them to get more in-depth knowledge on this topic.

Discuss Guava

Guava is an open source, Java based library developed by Google. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
This tutorial adopts a simple and intuitive way to describe the basic-to-advanced concepts of Guava and how to use its APIs.

EJB - Overview

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE platform have component based architecture to provide multi-tiered, distributed and highly transactional features to enterprise level applications.

EJB - Environment Setup

EJB is a framework for Java, so the very first requirement is to have JDK installed in your machine.

System Requirement

EJB - Create Application

To create a simple EJB module, we'll use NetBeans "New project" wizard. In example below, We'll create a ejb module project named Component.

EJB - Stateless Bean

A stateless session bean is a type of enterprise bean which is normally used to do independent operations. A stateless session bean as per its name does not have any associated client state, but it may preserve its instance state.

EJB - Stateful Bean

A stateful session bean is a type of enterprise bean which preserve the conversational state with client. A stateful session bean as per its name keeps associated client state in its instance variables. EJB Container creates a separate stateful session bean to process client's each request. As soon as request scope is over, statelful session bean is destroyed.

EJB - Persistence

EJB 3.0, entity bean used in EJB 2.0 is largely replaced by persistence mechanism. Now entity bean is a simple POJO having mapping with table.
Following are the key actors in persistence API

EJB - Message Driven Beans

A message driven bean is a type of enterprise bean which is invoked by EJB container when it receives a message from queue or topic. Message driven bean is a stateless bean and is used to do task asynchronously.

EJB - Annotations

Annotations were introduced in Java 5.0. Purpose of annotation is to attach additional information in the class or a meta-data of a class within its source code. In EJB 3.0, annotations are used to describe configuration meta-data in ejb classes. By this way EJB 3.0 eliminates the need to describe configuration data in configuration XML files.

EJB - Callbacks

Callback is a mechanism by which life cycle of an enterprise bean can be intercepted. EJB 3.0 specification has specified callbacks for which callback handler methods are to be created. EJB Container calls these callbacks.

EJB - Timer Service

Timer Service is a mechanism using which scheduled application can be build. For example, salary slip generation on 1st of every month. EJB 3.0 specification has specified @Timeout annotation which helps in programming the ejb service in a stateless or message driven bean. EJB Container calls the method which is annotated by @Timeout.

EJB - Dependency Injection

EJB 3.0 specification provides annotations which can be applied on fields or setter methods to inject dependencies. EJB Container uses the global JNDI registry to locate the dependency. Following annotations are used in EJB 3.0 for dependency injection.

EJB - Interceptors

EJB 3.0 provides specification to intercept business methods calls using methods annotated with @AroundInvoke annotation. An interceptor method is called by ejbContainer before business method call it is intercepting.

EJB - Embeddable Objects

EJB 3.0 provides option to embed JAVA POJO (Plain Old Java Object) into an entity bean and allows to map column names with the methods of the embedded POJO class. A java POJO to be embedded must be annotated as @Embeddable.

EJB - Blobs/Clobs

EJB 3.0 provides support for Blob and Clob types using @Lob annotation. Following java types can be mapped using @Lob annotation.

EJB - Transactions

A transaction is a single unit of work items which follows the ACID properties. ACID stands for Atomic, Consistent,Isolated and Durable.

EJB - Security

Security is a major concern of any enterprise level application. It includes identification of user(s) or system accessing the application and allowing or denying the access to resources within the application. In EJB, security can be declared in declarative way called declarative security in which EJB container manages the security concerns or Custom code can be done in EJB to handle security concern by self.

EJB - JNDI Bindings

JNDI stands for Java Naming and Directory Interface. It is a set of API and service interfaces. Java based applications use JNDI for naming and directory services. In context of EJB, there are two terms.

EJB - Entity Relationships

EJB 3.0 provides option to define database entity relationships/mappings like one to one, one to many, many to one and many to many relationships. Following are the relevant annotations.

EJB - Access Database

EJB 3.0, persistence mechanism is used to access the database in which container manages the database related operations. Developers can access database using jdbc api call directly in ejb business methods.
To demonstrate database access in ejb, we're going to do the following tasks.

EJB - Query Language

EJB 3.0, ejb query language is quite handy to write custom queries without worrying about underlying database details. It is quite similar to HQL, hibernate query language and is often referred by name EJBQL.
To demonstrate EJBQL in ejb, we're going to do the following tasks.

EJB - Exception Handling

EJB are part of enterprise applications which are normally distributed environment based. So apart from normal exceptions that can occur in code, in case of ejb, there can be exception like communication failure, security permissions, server down etc. EJB container considers exceptions in two ways.

EJB - Web Services

EJB 3.0 provides option to expose session ejb as a webservice. @WebService annotation is used to mark a class as a web service end point and @WebMethod is used to expose a method as web method to client.
@Stateless

EJB - Packaging Applications

Requirement of Packaging applications using EJB 3.0 are similar to that of J2EE platform. Ejb components are packaged into modules as jar files and are packaged into application enterprise archive as ear file. There are majorly three components of any enterprise application.

EJB Questions and Answers

EJB Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

EJB - Quick Guide

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE platform have component based architecture to provide multi-tiered, distributed and highly transactional features to enterprise level applications.

EJB - Useful Resources

The following resources contain additional information on EJB Please use them to get more in-depth knowledge on this topic.

Discuss EJB

Enterprise Java Beans (EJB) is a development architecture for building highly scalable and robust enterprise level applications to be deployed on J2EE compliant Application Server such as JBOSS, Web Logic etc.
EJB 3.0 is being a great shift from EJB 2.0 and makes development of EJB based applications quite easy.
This tutorial will give you great understanding on EJB concepts needed to create and deploy an enterprise level application up and running

Eclipse - Overview

What is Eclipse?

In the context of computing, Eclipse is an integrated development environment (IDE) for developing applications using the Java programming language and other programming languages such as C/C++, Python, PERL, Ruby etc.

Eclipse - Installation

Downloading Eclipse

You can download eclipse from http://www.eclipse.org/downloads/. The download page lists a number of flavors of eclipse.

Eclipse - Explore Windows

Parts of an Eclipse Window

The major visible parts of an eclipse window are −
  • Views
  • Editors (all appear in one editor area)
  • Menu Bar
  • Toolbar

Eclipse - Explore Menus

Typical Eclipse Menus

The typical menus available on the menu bar of an Eclipse window are −

Eclipse - Explore Views

About Views

Eclipse views allow users to see a graphical representation of project metadata. For example the project navigator view presents a graphical representation of the folders and files associated with a project and properties view presents a graphical representation of an element selected in another view or editor.

Eclipse - Perspectives

What is a Perspective?

An eclipse perspective is the name given to an initial collection and arrangement of views and an editor area. The default perspective is called java.

Eclipse - Workspaces

About Eclipse Workspace

The eclipse workspace contains resources such as −
  • Projects
  • Files
  • Folders

Eclipse - Create Java Project

Opening the New Java Project wizard

The New Java Project wizard can be used to create a new java project. There are many ways to open this wizard −

Eclipse - Create Java Package

Opening the New Java Package wizard

You can use the New Java Package wizard to create a Java package. The Java Package wizard can be opened in different ways −

Eclipse - Create Java Class

Opening the New Java Class Wizard

You can use the New Java Class wizard to create a Java class. The Java Class wizard can be invoked in different ways −

Eclipse - Create Java Interface

Opening the New Java Interface Wizard

The New Java Interface wizard can be used to create a new java interface. There are many ways of opening this wizard −

Eclipse - Create XML File

Opening the New XML File wizard

You can use the New XML file wizard to create an XML file. To invoke this wizard −
  • Click on the File menu and select New → Other or
  • Click on the new drop down box (Drop Down Box) select other or
  • Press ctrl + N

Eclipse - Java Build Path

Setting the Java Build Path

The Java build path is used while compiling a Java project to discover dependent classes . It is made up of the following items −

Eclipse - Run Configuration

Creating and Using a Run Configuration

The Run Configurations dialog allows you create multiple run configurations. Each run configuration can start an application. The Run Configuration dialog can be invoked by selecting the Run Configurations menu item from the Run menu.

Eclipse - Running Program

Running a Java Program

The quickest way to run a Java program is by using the Package Explorer view.
In the Package Explorer view −

Eclipse - Create Jar Files

Opening the Jar File wizard

The Jar File wizard can be used to export the content of a project into a jar file. To bring up the Jar File wizard −

Eclipse - Close Project

Why Close a Project?

An eclipse workspace can contain any number of projects. A project can be either in the open state or closed state.
Open projects −

Eclipse - Reopen Project

Reopening a Closed Project

To reopen a closed project, in the Package Explorer view, select the closed project and click on the Project menu and select Open Project.

Eclipse - Build Project

Building a Java Project

A project can have zero or more builders associated with it. A java project is associated with a java builder. To see the builders associated with a project −

Eclipse - Debug Configuration

Creating and Using a Debug Configuration

An eclipse debug configuration is similar to a run configuration but it used to start an application in the debug mode. Because the application is started in the debug mode the users are prompted to switch to the debug perspective.

Eclipse - Debugging Program

Debugging a Java Program

The quickest way to debug a Java program is to using the Package Explorer view. In the Package Explorer view −
  • Right click on the java class that contains the main method.
  • Select Debug As → Java Application.
The same action can be performed using the Package Explorer by selecting the class that contains the main method and clicking Alt + Shift + D, J.
Either actions mentioned above create a new Debug Configuration and use it to start the Java application.
If a Debug configuration has already been created you can use it to start the Java application by selecting Debug Configurations from the Run menu, clicking on the name of the debug configuration and then clicking on the Debug button.
Debug Program The Debug menu item on the Run menu can be used to restart the java application that was previously started in the debug mode.
Run Menu The shortcut key to launch the previously launched Java application in the debug mode is F11. When a java program is started in the debug mode, users are prompted to switch to the debug perspective. The debug perspective offers additional views that can be used to troubleshoot an application.
The java editor allows users to place break points in the java code. To set a break point, in the editor area right click on the marker bar and select Toggle Breakpoint.
Java Editor Breakpoints are shown on the marker bar. They are also visible in the Breakpoints View.
When the execution of code reaches a break point the JVM suspends the execution of the program. At this point, you can inspect the memory and execute the program in a controlled manner.
When the execution of a program is paused, the debug view can be used to inspect the call stack.
Debug Call Stack The variables view can be used to inspect the value of variables.
Value of Variable The run menu has menu items that allow you to Resume execution, step over a line of code, step into a function etc.
Run Menu Items The picture given above shows the shortcut keys associated with actions such as Resume, Step Into and Step Over, etc.

Eclipse - Preferences

Setting Preferences

The Preferences dialog allows Eclipse users to manage their preferences. This dialog box is managed by the framework but any plug-in can add multiple pages to the dialog box.

Eclipse - Content Assist

Using Content Assist

Within an editor, content assist helps reduce the characters typed by providing a context sensitive list of possible completions to the characters already typed. The context assist can be invoked by clicking Ctrl + Space.

Eclipse - Quick Fix

Using Quix Fix

As you type characters into an eclipse editor it analyzes the document content for potential error and warnings. The java editor uses the java syntax to detect errors in the code. When it finds error or warning, it

Eclipse - Hover Help

Using Hover Help

The java editor is associated with different type of hovers. A hover provides additional information about the element under the mouse pointer. All the hovers associated with a java editor can be seen in the Java editor Hovers preference page.

Eclipse - Search Menu

Searching the Workspace

The Eclipse search dialog box allows you to search for files that contain a literal or a character pattern in the entire workspace, a set of projects, a specific project or folders selects in the package explorer view.
The search dialog box can be invoked by −

Eclipse - Navigation

Navigating the Eclipse Workspace

The navigate menu provides a number of menu items that allow you to quickly locate and navigate to a resource.

Eclipse - Refactoring

Refactoring using Eclipse

Renaming a class that is used widely throughout a project could take a lot of time but the Eclipse refactoring wizard makes the job easier by automatically detecting all dependencies on the class being renamed and modifying them also.

Eclipse - Add Bookmarks

About Bookmarks

Eclipse editors allow you to place a book mark on any line within the editor. You can use bookmarks to serve as reminders and quickly navigate to any line in a file.

Eclipse - Task Management

Managing Tasks

Programmers like to place TODO markers in their code which serves as a reminder for tasks that need to be completed. Comments in the Java code that has the word TODO in them are recognized as task and shown on the marker bar and in the Tasks view.

Eclipse - Install Plugins

Locating and Installing Plug-ins

The Eclipse platform which provides the foundation for the Eclipse IDE is composed of plug-ins and is designed to be extensible using additional plug-ins.

Eclipse - Code Templates

Using Code Templates

Code templates help reduce typing time by inserting code into the editor. Each code template is given a short literal. Typing the literal into the editor window and press Ctrl + Space brings up a dialog box from which a code template associated with that literal can be selected.

Eclipse - Shortcuts

About Shortcuts

You can navigate the Eclipse User Interface using only the keyboard by −
  • Using mnemonics associated with menus and menu items.
  • Using mnemonics associated with controls in a dialog box or view or editor.
  • Using accelerators associated with actions such as menu items and buttons on the toolbar.

Eclipse - Restart Option

Restarting Eclipse

The restart option allows users to restart eclipse. To restart eclipse, click on the File menu and select the Restart menu item.

Eclipse - Tips & Tricks

TIP #1 − DISCOVERING SHORTCUT KEYS
  • Press Ctrl + Shift + L to open a widget that shows all the shortcut keys.

Eclipse - Web Browsers

Internal Web Browser

The Internal Web Browser view allows you to surf the internet from within the Eclipse Workbench Window. To activate the Internal Web Browser view click on the Window and select Show View → Other.
In the filter text box of the Show View dialog box enter browser. From the tree select Internal Web Browser and click OK.

Eclipse - Quick Guide

Eclipse - Overview

What is Eclipse?

In the context of computing, Eclipse is an integrated development environment (IDE) for developing applications using the Java programming language and other programming languages such as C/C++, Python, PERL, Ruby etc.

Eclipse - Useful Resources

The following resources contain additional information on Eclipse. Please use them to get more in-depth knowledge on this topic.

Discuss Eclipse

Eclipse is an integrated development environment (IDE) for Java and other programming languages like C, C++, PHP, and Ruby etc.

EasyMock - Overview

What is Mocking?

Mocking is a way to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a functionality. Mock objects do the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it.

EasyMock - Environment Setup

EasyMock is a framework for Java, so the very first requirement is to have JDK installed in your machine.

EasyMock - First Application

Before going into the details of the EasyMock Framework, let’s see an application in action. In this example, we've created a mock of Stock Service to get the dummy price of some stocks and unit tested a java class named Portfolio.

EasyMock - JUnit Integration

In this chapter, we'll learn how to integrate JUnit and EasyMock together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division.

EasyMock - Adding Behavior

EasyMock adds a functionality to a mock object using the methods expect() and expectLassCall(). Take a look at the following code snippet.
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);

EasyMock - Verifying Behavior

EasyMock can ensure whether a mock is being used or not. It is done using the verify() method. Take a look at the following code snippet.
//activate the mock
EasyMock.replay(calcService);

EasyMock - Expecting Calls

EasyMock provides a special check on the number of calls that can be made on a particular method. Suppose MathApplication should call the CalculatorService.serviceUsed() method only once, then it should not be able to call CalculatorService.serviceUsed() more than once.

EasyMock - Varying Calls

EasyMock provides the following additional methods to vary the expected call counts.
  • times (int min, int max) – expects between min and max calls.
  • atLeastOnce () – expects at least one call.
  • anyTimes () – expects an unrestricted number of calls.

EasyMock - Exception Handling

EasyMock provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet.
//add the behavior to throw exception

EasyMock - createMock

So far, we've used annotations to create mocks. EasyMock provides various methods to create mock objects. EasyMock.createMock() creates mocks without bothering about the order of method calls that the mock is going to make in due course of its action.

EasyMock - createStrictMock

EasyMock.createStrictMock() creates a mock and also takes care of the order of method calls that the mock is going to make in due course of its action.

Syntax

calcService = EasyMock.createStrictMock(CalculatorService.class);

Example

Step 1: Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}
Step 2: Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
   private CalculatorService calcService;

   public void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   public double add(double input1, double input2){
      return calcService.add(input1, input2);  
   }
   
   public double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   public double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   public double divide(double input1, double input2){
      return calcService.divide(input1, input2);
   }
}
Step 3: Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add(). When we create a mock object using EasyMock.createStrictMock(), the order of execution of the method does matter.
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(EasyMockRunner.class)
public class MathApplicationTester {
 
   private MathApplication mathApplication;
   private CalculatorService calcService;
   
   @Before
   public void setUp(){
      mathApplication = new MathApplication();
      calcService = EasyMock.createStrictMock(CalculatorService.class);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtract(){
      
      //add the behavior to add numbers
      EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
      
      //subtract the behavior to subtract numbers
      EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0);
      
      //activate the mock
      EasyMock.replay(calcService); 
 
      //test the subtract functionality
      Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0);
      
      //test the add functionality
      Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
      
      //verify call to calcService is made or not
      EasyMock.verify(calcService);
   }
}
Step 4: Execute test cases
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
File: TestRunner.java

EasyMock - createNiceMock

EasyMock.createNiceMock() creates a mock and sets the default implementation of each method of the mock. If EasyMock.createMock() is used, then invoking the mock method throws assertion error.

EasyMock - EasyMockSupport

EasyMockSupport is a utility or helper class for test classes. It provides the following functionalities:
  • replayAll() – Registers all the created mocks in one batch.
  • verifyAll() – Verifies all the mock operations in one batch.
  • resetAll() – Resets all the mock operations in one batch.

EasyMock - Quick Guide

EasyMock - Overview

What is Mocking?

Mocking is a way to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a functionality. Mock objects do the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it.

EasyMock

EasyMock - Useful Resources

The following resources contain additional information on EasyMock. Please use them to get more in-depth knowledge on this topic.

Discuss EasyMock

EasyMock is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. EasyMock is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.