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.samplesWhen 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:
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);
}
}
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.