A short example Test Driven Development session where I code FizzBuzz.
FizzBuzz is often used as a programming interview question and as a Kata for practicing your coding.
The GitHub code repository with the Java code for this exercise is available at:
https://github.com/eviltester/fizzbuzz
Read the blog post for the video:
http://blog.eviltester.com/2018/03/tdd-test-driven-development-java-junit.html
4. First I:
created a test class
copied in the rules as a comment
formatted the rules to make it easy to understand
added some examples so that I could understand
6. This forced me to create the FizzBuzzConverter class and convert
method.
I added a second assertion to this test:
Assert.assertEquals("2", fizzBuzz.convert(2));
7. This forced me to actually implement the default code in convert:
return String.valueOf(toConvertToFizzBuzz);
8. My Second Test
The second test was:
@Test
public void fizzBuzzConvertorMultiplesOfThree(){
FizzBuzzConverter fizzBuzz = new FizzBuzzConverter();
Assert.assertEquals("Fizz", fizzBuzz.convert(3));
}
9. This forced me to implement the '3' division rule:
if(toConvertToFizzBuzz%3==0){
return "Fizz";
}
11. Much the same as the condition for number 3:
if(toConvertToFizzBuzz%5==0){
return "Buzz";
}
12. At this point my convert method looks
as follows:
public String convert(int toConvertToFizzBuzz) {
if(toConvertToFizzBuzz%5==0){
return "Buzz";
}
if(toConvertToFizzBuzz%3==0){
return "Fizz";
}
return String.valueOf(toConvertToFizzBuzz);
}
14. Avoid Temptation to Over‐Complicate
should I add a flag to check for fizz and buzz?
should I have a set of nested ifs?
perhaps I can use a tertiary operator for some 'magic'
keep it simple:
if(toConvertToFizzBuzz%15==0){
return "FizzBuzz";
}
19. BIO
Alan is a test consultant who works at a technical level using
techniques from psychotherapy and computer science. In his spare
time Alan is currently programming a multi‐user text adventure
game, a Twitter Client and some buggy JavaScript games in the
style of the Cascade Cassette 50. Alan is the author of the books
"Dear Evil Tester", "Java For Testers" and "Automating and Testing a
REST API". Alan's main website is compendiumdev.co.uk and he
mostly blogs at blog.eviltester.com