Java Reference
In-Depth Information
expect( mockAccountManager.findAccountForUser( "1" ) )
.andReturn( senderAccount );
expect( mockAccountManager.findAccountForUser( "2" ) )
.andReturn( beneficiaryAccount );
G
// we're done defining the expectations
replay( mockAccountManager );
H
AccountService accountService = new AccountService();
accountService.setAccountManager( mockAccountManager );
accountService.transfer( "1", "2", 50 );
I
J
assertEquals( 150, senderAccount.getBalance() );
assertEquals( 150, beneficiaryAccount.getBalance() );
}
@After
public void tearDown()
{
verify( mockAccountManager );
}
}
As you see, listing 7.15 is pretty much the same size as listing 7.4, but we are spared
the writing of any additional mock classes. We start the listing by defining the imports
from the EasyMock library that we need B . EasyMock relies heavily on the static-
import feature of Java 5+. In C we declare the object that we'd like to mock.
Notice that our AccountManager is an interface. The reason behind this is simple:
the core EasyMock framework can mock only interface objects. In D we call the
createMock method to create a mock of the class that we want. In E , as in listing 7.4,
we create two account objects that we're going to use in our tests. After that we
start declaring our expectations. With EasyMock we declare the expectations in two
ways. When the method return type is void, we call it on the mock object (as in
F ), or when the method returns any kind of object, then we need to use the
expect and andReturn methods from the EasyMock API G . Once we've finished
defining the expectations, we need to call the replay method to announce it H .
In I we call the transfer method to transfer some money between the two
accounts, and in J we assert the expected result. The @After method, which gets
executed after every @Test method, holds the verification of the expectations. With
EasyMock we can call the verify method with any mock object
1)
1)
, to verify that
the method-call expectations we declared were triggered.
That was pretty easy, wasn't it? So how about moving a step forward and revising a
more complicated example? No problem; listing 7.16 shows the reworked WebClient
test from listing 7.12.
What we'd like is to test the getContent method of the WebClient . For this pur-
pose we need to mock all the dependencies to that method. In this example we have
two dependencies: one is the ConnectionFactory and one is the InputStream . It
looks like there's a problem because EasyMock can mock only interfaces, and the
InputStream is a class.
 
 
Search WWH ::




Custom Search