Last time I finished with a failing test case which drove the development to a phase where I had to deal with a sentence instead of a word. The fix was not a big deal, but I ended up with a method in SimpleTextMunger which did three things:
// ... public String execute(String sentence) { StringBuilder mungedSentence = new StringBuilder(); for (String word : sentence.split(" ")) { mungedSentence.append(mungeAWord(word)).append(" "); } return mungedSentence.toString().trim(); } private String mungeAWord(String word) { // ... prior content of the execute(String) method }
- convert the sentence into words
- munge a word
- collect the munged words and create the new sentence
The first and the third one belong together because they work with a sentence, so I created two classes – SentenceHelper and Munger -, which are used by the SimpleTextMunger:
public class SimpleTextMunger { public String execute(String sentence) { SentenceHelper sentenceHelper = new SentenceHelper(); Munger munger = new Munger(); List words = sentenceHelper.split(sentence); for (int i = 0; i < words.size(); i++) { words.set(i, munger.munge(words.get(i))); } return sentenceHelper.join(words); } } class Munger { public String munge(String word) { // the same as before } } class SentenceHelper { public List split(String sentence) { // ... } public String join(List words) { // ... } }
One day, I’d like to write unit tests, mocks – you know, the whole package -, so I must move those two new statements out of the scope of the execute method. Fortunately, I already have spring, so I’m just going to hack a solution together to see whether it works or not. I can do it now, because all the scenarios are green.
This is the best thing about scenarios and BDD, that I can do experimenting, spiking, refactoring or anything else without changing the test cases. Try to do it with unit tests: the moment you move something, the mocks will turn red and you have to do a lot of unnecessary work by fixing them. Read more »