Breaking Up Methods to Avoid Mock Objects
Problem
You want to test a method without resorting to the complexity of mock objects.
Solution
Split the method into smaller pieces, ensuring that each piece performs one task. Small, single-purpose methods improve code quality in addition to making them testable.
Discussion
Example 6-12 shows a method that is hard to test. It
is hard because you must create a mock ResultSet
implementation in order to write your tests.
Example 6-12. Hard to test
// fetch an account type code from the database and convert it
// into one of the Account constants
int getAccountType(ResultSet rs, String acctTypeColName)
throws SQLException, DataSourceException {
String acctStr = rs.getString(acctTypeColName);
if ("SA".equals(acctStr)) {
return Account.SAVINGS;
}
if ("CH".equals(acctStr)) {
return Account.CHECKING;
}
throw new DataSourceException("Unknown account type: " + acctStr);
}The fundamental problem is that this method performs two tasks,
rather than one. It is also a little messy because it throws two
types of exceptions. The first task is to retrieve data from the
ResultSet. The second task is to convert that data
into some other form.
When confronted with a method like this, do not try to write a sophisticated unit test. Instead, first try to simplify the method. Example 6-13 shows a simplified version of this method. It is now assumed that the caller obtains the account code from the database before calling this method, whose sole purpose is converting ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access