Java Reference
In-Depth Information
The next section demonstrates the use of some of the most popular open source
mocking frameworks—they're powerful enough for our needs, and we don't need to
implement our mocks from the beginning.
7.6
Introducing mock frameworks
So far we've been implementing the mock objects we need from scratch. As you can
see, it's not a tedious task but rather a recurring one. You might guess that we don't
need to reinvent the wheel every time we need a mock. And you're right—there are
many good projects already written that can help us facilitate the usage of mocks in
our projects. In this section we take a closer look at two of the most widely used mock
frameworks: the EasyMock and the
JM
ock. We try to rework the example
HTTP
con-
nection application so that we can demonstrate how to use the two frameworks.
7.6.1
Using EasyMock
EasyMock (
http://easymock.org/
) is an open source framework that provides useful
classes for mocking objects. To use the framework you need to download the zip
archive from the website of the project, unpack it somewhere, and include the con-
tained easymock.jar in your classpath.
To show you how easy it is to construct mock objects in your test cases using Easy-
Mock, we revise some of the mocks we constructed in the previous sections. We start
with a simple one: reworking the
AccountService
test from listing 7.2. See listing 7.15.
Listing 7.15
Reworking the
TestAccountService
test using EasyMock
[...]
import static
org.easymock.EasyMock.createMock;
import static
org.easymock.EasyMock.replay;
import static
org.easymock.EasyMock.expect;
import static
org.easymock.EasyMock.verify;
B
public class
TestAccountServiceEasyMock
{
private
AccountManager mockAccountManager;
C
@Before
public void
setUp()
{
mockAccountManager = createMock( "mockAccountManager",
AccountManager.class );
}
D
@Test
public void
testTransferOk()
{
Account senderAccount =
new
Account( "1", 200 );
Account beneficiaryAccount =
new
Account( "2", 100 );
E
// Start defining the expectations
mockAccountManager.updateAccount( senderAccount );
mockAccountManager.updateAccount( beneficiaryAccount );
F