Java Reference
In-Depth Information
oneOf( mockAccountManager ).findAccountForUser( "2" );
will( returnValue( beneficiaryAccount ) );
oneOf( mockAccountManager ).updateAccount( senderAccount );
oneOf( mockAccountManager )
.updateAccount( beneficiaryAccount );
}
} );
AccountService accountService = new AccountService();
accountService.setAccountManager( mockAccountManager );
accountService.transfer( "1", "2", 50 );
J
1)
assertEquals( 150, senderAccount.getBalance() );
assertEquals( 150, beneficiaryAccount.getBalance() );
}
}
As always, we start the listing by importing all the necessary objects we need B . As you
can see, unlike EasyMock, the JM ock framework doesn't rely on any static import fea-
tures. Luckily enough, the JM ock framework provides a JU nit 4 runner 5 that will facili-
tate a lot. In C we instruct JU nit to use the JM ock runner that comes with the
framework. In D we declare the context Mockery object that will serve us to create
mocks and to define expectations. In E we declare the AccountManager that we'd like
to mock. Just like EasyMock, the core JM ock framework provides mocking only of
interfaces. In the @Before method, which gets executed before each of the @Test
methods, we create the mock by means of the context object F . As in any of the previ-
ous listings, we declare two accounts that we're going to use to transfer money
between G . Notice that this time the accounts are declared final . This is because we
use them in an inner class defined in a different method. In H we start declaring the
expectations by constructing a new Expectations object. In I we declare the first
expectation, each expectation having the following form:
invocation-count (mock-object) .method(argument-constraints);
inSequence(sequence-name);
when(state-machine.is(state-name));
will(action);
then(state-machine.is(new-state-name));
All the clauses are optional, except for the bold ones: invocation-count and mock-
object . We need to specify how many invocations will occur and on which object.
After that, in case the method returns some object, we can declare the return object
by using the will(returnValue()) construction.
In J we start the transfer from one account to the other, and after that we assert
the expected results . It's as simple as that! But wait; what happened with the verifi-
cation of the invocation count? In all of the previous examples we needed to verify
that the invocations of the expectations happened the expected number of times.
1)
5
You can see how to implement a custom JUnit runner in appendix B of the topic.
 
 
 
 
Search WWH ::




Custom Search