EasyMock Partial Mock With Examples

EasyMock supports creating partial mock, where we can specify the methods that will be mocked. If any other method is called, object real method will get invoked.

EasyMock Partial Mock Example

Let’s say we have a utility class defined as:

We want to mock toUpperCase() method but not print() method. We can use partialMockBuilder() method to achieve this. We will also have to use addMockedMethod() to provide the list of methods to be mocked.

If you want to mock multiple methods in the partial mock, use addMockedMethods() with the method names as argument.

EasyMock Partial Mock Constructor

We can call a class constructor too while creating the partial mock. This is useful when the real methods are using some properties set through the constructor.

For calling a partial mock constructor, we can use withConstructor() and withArgs() method. There are multiple overloaded withConstructor() methods, chose one that fits your class constructor requirements.

Let’s say we have a Data class defined as:

We want to mock only decode() method. But since print() and encode() methods are using object property being set through the constructor, we will have to create partial mock and call its constructor too.

Summary

EasyMock partial mock is helpful when we are interested in testing only a few methods of the class. It’s very similar to creating partial mock in Mockito using Mockito Spy.

You can checkout complete project and more EasyMock examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: