Wednesday, May 26, 2010

Mock Test cases concept

Idea behind introducing Mock test cases is to avoind dependancies and do the unit testing properly.Here i have given an example to get idea.

public interface DataAccess {
BigDecimal getPriceBySku(String sku);
public interface PricingService {
void setDataAccess(DataAccess dataAccess);
BigDecimal getPrice(String sku) throws Exception;
public class PricingServiceImpl implements PricingService {
private DataAccess dataAccess;
public void setDataAccess(DataAccess dataAccess) {
this.dataAccess = dataAccess;
public BigDecimal getPrice(String sku) throws Exception {
final BigDecimal price = this.dataAccess.getPriceBySku(sku);
if (price == null) {
throw new Exception();
return price;

Lets say we want to write a test case for the PricingServiceImplclass.So we need t o have a concreate implimentation of DataAccess class. If we have get the use of a concreate classs object then our testing is no longer a unit testing.(since it is depemding on that concreate class's object and there can be some test failures due to eoors in that class).
So to avoid that dependancy what we can do is with out using a concreate class we can inject DataAccess implementation using Jmock. So our testing is not depend on the implimentation of DataAccess class and we can perform a proper unit test.

we can do it as following.

private PricingService systemUnderTest;
private DataAccess mockedDependency;
private Mockery mockingContext;
public void doBeforeEachTestCase() {
mockingContext = new JUnit4Mockery();
systemUnderTest = new PricingServiceImpl();
mockedDependency = mockingContext.mock(DataAccess.class); // here we are injecting

1 comment:

  1. following link will give more details about the mock expectations.

    mock example that i used to explain