Information Technology Reference
In-Depth Information
In Listing 6-15, the assumption is made that the fix will cause
the code to no longer throw an exception. This is true, but it's
only part of the whole story.
• Once a fix has been made in the code under test, the failing test
works; however, it doesn't actually verify the change in behavior.
At this point, because the test case works, most people don't go
back to update it. In our case, in order to fix the defect we in essence
need to break the test, which is the opposite of what defect-driven
development advocates.
Examining the code closely reveals that we need to check for an
empty list before attempting to grab the first element. We're left with a
design choice at this point—should the code return null , return an
empty Word , or throw an exception? The decision is made to return
null if the parameter value cannot be retrieved from the database via
Hibernate (see Listing 6-16).
LISTING 6-16
Updated Code That Fixes the Defect
public IWord findWord(String word) throws FindException{
Session sess = null;
try{
sess = WordDAOImpl.sessFactory.getHibernateSession();
final Query qry = sess.getNamedQuery("word.finder.bySpelling");
qry.setString("spelling", word);
final List lst = qry.list();
IWord wrd = null;
if(lst.size() > 0){
wrd = (IWord)lst.get(0);
}
sess.close();
return wrd;
}catch(Throwable thr){
try{sess.close();}catch(Exception e){}
throw new FindException("Exception while finding word: "
+ word + " "+ thr.getMessage(), thr);
}
}
With the code under test conceivably fixed, the test is run again
and this time it fails. This next decision is what differentiates this
approach from others—in fixing our test case, we will assert the new
Search WWH ::




Custom Search