Java Reference
In-Depth Information
JUnit best practices: don't write business logic in mock objects
The most important point to consider when writing a mock is that it shouldn't have
any business logic. It must be a dumb object that does only what the test tells it
to do. It's driven purely by the tests. This characteristic is exactly the opposite of
stubs, which contain all the logic (see chapter 6).
There are two nice corollaries. First, mock objects can be easily generated, as
you'll see in following chapters. Second, because mock objects are empty shells,
they're too simple to break and don't need testing themselves.
method updates an account but doesn't return any value D . We do nothing. When
it's called by the transfer method, it will do nothing, as if the account had been cor-
rectly updated.
We're now ready to write a unit test for AccountService.transfer . Listing 7.4
shows a typical test using a mock.
Listing 7.4
Testing transfer with MockAccountManager
[...]
public class TestAccountService {
@Test
public void testTransferOk() {
MockAccountManager mockAccountManager = new MockAccountManager();
Account senderAccount = new Account("1", 200);
Account beneficiaryAccount = new Account("2", 100);
mockAccountManager.addAccount("1", senderAccount);
mockAccountManager.addAccount("2", beneficiaryAccount);
AccountService accountService = new AccountService();
accountService.setAccountManager(mockAccountManager);
accountService.transfer("1", "2", 50);
assertEquals(150, senderAccount.getBalance());
assertEquals(150, beneficiaryAccount.getBalance());
}
}
As usual, a test has three steps: the test setup B , the test execution C , and the verifi-
cation of the result D . During the test setup, we create the MockAccountManager object
and define what it should return when called for the two accounts we manipulate (the
sender and beneficiary accounts). We've succeeded in testing the AccountService
code in isolation of the other domain object, AccountManager , which in this case didn't
exist, but which in real life could have been implemented using JDBC .
At this point in the chapter, you should have a reasonably good understanding of
what a mock is. In the next section, we show you that writing unit tests with mocks
leads to refactoring your code under test—and that this process is a good thing!
B
C
D
 
 
 
 
Search WWH ::




Custom Search