Tuesday, 29 November 2011

Easymock - create partial mocks

EasyMock is a very useful tool allowing to mock all objects that the tested unit of code depends on. This is of course assuming you write your code in the way that allows that e.g. using dependency injection pattern.

It is also possible to mock only a part of the object e.g. single method and leave original implementation for the remaining part. Such object is called a 'partial mock'.

The following Java code presents how to create such partial mock:
package com.blogspot.fczaja.samples

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

public class PartialMockTests
{
class PartialMock
{
void foo()
{
// Code inside foo() will not be invoked while testing
System.out.println("foo");
}

void boo()
{
// Code inside boo should be invoked
System.out.println("boo");
foo();
}
}

@Test
public void testPartialMock()
{
PartialMock partialMock = EasyMock
.createMockBuilder(PartialMock.class) //create builder first
.addMockedMethod("foo") // tell EasyMock to mock foo() method
.createMock(); // create the partial mock object

// tell EasyMock to expect call to mocked foo()
partialMock.foo();
EasyMock.expectLastCall().once();
EasyMock.replay(partialMock);

partialMock.boo(); // call boo() (not mocked)

EasyMock.verify(partialMock);
}
}
When executing our test the method foo() of the object will be mocked and method boo() will be invoked normally. The console output of that test would be:
boo

I'm using this technique when I want to test a single method, that calls other methods in the same class. I can mock all other methods so they behave like methods form other mocked objects.

2 comments:

PM said...

Thanks for the blog. Exactly what I was looking for and helped me move on after struggling for 2 days with the issue.

Anonymous said...

1. Does it supports returned values?
2. Does it supports parameters?