Below is a method that I’m having a hard time figuring out how to test using JUnit.
This method is difficult to test because it depends on the results of other methods (e.g. getClosestDcoumentCode).
Based on my reading of JUnit, this suggests I should refactor the method. But how? And if refactoring is not necessary, how do you test a method that depends on other methods?
Thank you,
Elliott
private static String findPrincipal(List<DocumentKey> documentkeys_) {
Hashtable<String, Integer> codecounts = new Hashtable<String, Integer>();
for (DocumentKey document : documentkeys_) {
int x = 0;
String closestCode = getClosestDocumentCode(document.candidates);
if (closestCode == null) continue;
int thecount = 0;
if (codecounts.containsKey(closestCode))
thecount = codecounts.get(closestCode);
if (document.hasKey)
thecount += 2;
else
thecount++;
codecounts.put(closestCode, new Integer(thecount));
x++;
}
String closestCode = getClosestCode(codecounts);
return closestCode;
}
It sounds to me like
getClosestCodeandgetClosestDocumentCodebelong to a different set of responsibilities than thefindPrincipalmethod. So you’ll want to begin by separating these into two different classes. Create an interface for each class to implement. The class that implements thefindPrincipalmethod can then rely on the other interface as a constructor argument, like this:Now it should be easy to create another class the implements the
CodeFinderinterface, either manually or using a Mocking framework. You can then control the results of each call togetClosestCodeandgetClosestDocumentCode, and ensure that each of these methods gets called with exactly the arguments you expect it to be called with.