Make everything as simple as possible, but not simpler. -Albert Einstein 

Home EasyMock Unit Testing with EasyMock
formats

Unit Testing with EasyMock



Summary: Unit testing involves testing business logic in isolation.  In many situations,  Java classes  will have a natural dependency on other classes.  These dependent classes can be replaced with mock objects.   Mock objects are instances of test provided classes.

For example, let’s say you would like to unit test an algorithm that calculates a company’s credit score based on credit history.  With EasyMock , it is  unnecessary to use the actual external service to retrieve the company’s credit information.  EasyMock is an open source framework that  dynamically generates mock objects using  developer provided interfaces.

Prerequisites: If you would like to obtain this article’s complete sample, it may be obtained from our GitHub repository.  All samples are Maven based java project

Let’s Get Started: To showcase some of EasyMock’s features we will implement  basic shopping cart functionality normally found in an online store.   Our Item object represents an individual product in the store. The ShoppingCart object will contain  Items  and calculate the total price of a user’s shopping cart. We will  use EasyMock  in conjunction with JUnit to unit test the ShoppingCart.calculateTotalPrice() method.

Listing 1: GroceryItem.java

package techbysample.easymock.sample1.model;

/**
*  TechbySample.com
*/

public class Item {

private String name;
private int quantity;

public Item(String name, int quantity) {
super();
this.name = name;
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

}

Listing 2: ShoppingCart.java

package techbysample.easymock.sample1;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import techbysample.easymock.sample1.model.Item;

/**
*  TechbySample.com
*/

public class ShoppingCart {

private String name;
private Store store = null;

private List items = new ArrayList();

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List getItems() {
return items;
}

public void setItems(List items) {
this.items = items;
}

public void addItem(Item item)
{
items.add(item);
}

public void setStore(Store store)
{
this.store=store;
}

public Store getStore()
{
return (this.store);
}

public Double calculateTotal()
{
Double total = 0.0;
for (Item item : this.items) {
total+= (store.getPrice(item.getName()) * item.getQuantity());
}

DecimalFormat decim = new DecimalFormat("0.00");
Double price = Double.parseDouble(decim.format(total));

return price;
}
}

How EasyMock Works:  In Listing 2: ShoppingCart, line 55, you will notice the ShoppingCart.calculateTotal() method depends on Store object to retrieve price information for store items.    In order to test the ShoppingCart.calculateTotal() method, we do not prefer to fetch the item’s  from a live service.  This is where EasyMock’s value is demonstrated.  EasyMock accepts a Java interface that depicts the behavior of the dependent, external class. In our example, EasyMock will use the Store interface to dynamically generate a mock, concrete class relieving us from writing our own implementation.

Please refer to Listing 3: ShoppingCartTest.java for the following explanation:

In line 24,  We request that EasyMock  create a mock object for the Store interface.

In line 25, We pass the dynamically created Store instance to the ShoppingCart object via ShoppingCart.setStore().

In lines 33-34, We specify how our mock object should behave when invoked.  The getPrice () method will return 1.99 when called with “Mead Spiral Bound Notebook, College Rule” input parameter.  In addition, the getPrice() method will return 499.99 when called with the “Kindle Fire HD 8.9” input paramteter.

In line 37, EasyMock.replay(store)  method is called to make the Mock object available for testing.

Listing 3: ShoppingCartTest.java

package techbysample.easymock.sample1;

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import techbysample.easymock.sample1.model.Item;

/**
 *  TechbySample.com
 */
public class ShoppingCartTest  {

	public ShoppingCart cart = null;
	public Store storeMock = null;

	@Before
	public void initialize()
	{
		cart = new ShoppingCart();
		storeMock = EasyMock.createMock(Store.class);
		cart.setStore(storeMock);
	}

	@Test
    public void testShoppingCart()
	{

		//Initialize mock object with the expected values
		EasyMock.expect(storeMock.getPrice("Mead Spiral Bound Notebook, College Rule")).andReturn(1.99);
		EasyMock.expect(storeMock.getPrice("Kindle Fire HD 8.9")).andReturn(499.99);

		//Begin testing the ShoppingCart
		EasyMock.replay(storeMock);

		Item item1 = new Item("Mead Spiral Bound Notebook, College Rule", 3);
		Item item2 = new Item("Kindle Fire HD 8.9",1);

		cart.addItem(item1);
		cart.addItem(item2);

		double total = cart.calculateTotal();

		System.out.println("Total price of items in shopping cart: $"+total);
		assertEquals("Result",505.96, total,0);
	}

	@After
	public void cleanup()
	{
		cart=null;
		storeMock=null;
	}

}

Unit testing EasyMock:

From the ‘easymock-sample1′ project directory, type:

mvn -Dtest=ShoppingCartTest test

You should see a result similar to the following output:
——————————————————-
T E S T S
——————————————————-
Running techbysample.easymock.sample1.ShoppingCartTest
Total price of items in shopping cart: $505.96
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.414 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 6.145s
[INFO] Finished at: Fri Sep 28 23:01:45 CDT 2012
[INFO] Final Memory: 5M/10M
[INFO] ————————————————————————

Resources:
EasyMock Web site
Official TechBySample GitHub repository

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

© Techbysample.com, all rights reserved.