1. Test-Driven Development
Coding Dojo
Pietro Di Bello
pietro.di.bello@xpeppers.com
@pierodibello
@xpeppers
JUG Trentino Alto-Adige
Agosto 2012
2. Che cos’è il TDD?
è una tecnica di design in cui lo sviluppo di una
funzionalità è guidato dalla scrittura di uno o più unit
test
• si basa sull'uso di unit test
• lo sviluppo del codice è guidato dalla scrittura di
unit test che devono essere di volta in volta verificati
• il test viene scritto ed eseguito PRIMA del codice
stesso che consentirà di verificarlo
3. Write a test
public class AdderTest {
@Test
public void testTwoPlusThree() {
Adder a = new Adder();
assertEquals(5, a.add(2, 3));
}
}
4. Now it compiles
public class AdderTest {
@Test
public void testTwoPlusThree() {
Adder a = new Adder();
assertEquals(5, a.add(2, 3));
}
}
public class Adder {
public int add(int a, int b) { return 0; }
}
5. Red bar!
public class AdderTest {
@Test
public void testTwoPlusThree() {
Adder a = new Adder();
assertEquals(5, a.add(2, 3));
}
}
public class Adder {
public int add(int a, int b) { return 0; }
}
Expected 5, was 0
6. Do the simplest thing
public class AdderTest {
@Test
public void testTwoPlusThree() {
Adder a = new Adder();
assertEquals(5, a.add(2, 3));
}
}
public class Adder {
public int add(int a, int b) { return 5; }
}
7. Refactor
public class AdderTest {
@Test
public void testTwoPlusThree() {
Adder a = new Adder();
assertEquals(5, a.add(2, 3));
}
}
public class Adder {
public int add(int a, int b) { return a+b; }
}
8. The procedure
1. Write a test
2. Make it compile
Expected 5, was 0
3. Make it pass quickly
4. Refactor to remove duplication
11. TDD: why?
• Per abbattere la complessità
• Consente di ridurre la soluzione di un problema
complesso in tanti problemi più semplici (divide et
impera)
12. TDD: why?
Ogni test rappresenta una opportunità di porre una
domanda sul sistema, la cui risposta ci porterà ad un
maggiore consolidamento della conoscenza e una
riduzione dell'unknown
13. TDD: why?
When we write a test, we imagine the perfect
interface for our operation.We are telling ourselves
a story about how the operation will look from the
outside.
Our story won't always come true, but it's better to
start from the best-possible application program
interface (API) and work backward than to make
things complicated, ugly, and "realistic" from the
get-go.
Kent Beck
14. Simple design
The code is simple enough when it:
0. Runs all the tests
1. Contains no duplication
2. Expresses every idea that we need to express
3. Has the minimum number of classes and functions
(In this order)
Kent Beck, Extreme Programming Explained
15. Il primo test
• deve essere piccolo
• il più semplice possibile
• ad es possiamo selezionare un caso
degenere
• tracciamo i primi contorni di una API ad un
dettaglio molto più fine di quanto siamo abituati
solitamente
18. Il prossimo test
Trattiamo ogni test come una nuova occasione per
imparare e ridurre la complessità sul modello del
problema
Qual’è la prossima domanda a cui vogliamo rispondere?
20. Uso della to-do list
• Utile per gestire la complessità
• elencare i diversi aspetti del problema
• NON si elencano i test da implementare
• non è TDD
• Riduce lo stress
• Bussola per farci capire a che punto siamo e non ci
perdere la strada
• Se mi viene in mente qualcosa la scrivo nella todolist e
continuo sulla mia strada senza perdere focus
• => tecnica del Pomodoro
23. What’s a kata?
A kata is meant to be memorized.
Students of a kata study it as a form, not as a conclusion.
It is not the conclusion of the kata that matters, it's the
steps that lead to the conclusion.
Bob Martin (http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata)
24. The Bowling Game Kata
By Robert Martin “Uncle Bob”
http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata
25. Il punteggio del bowling
Ci sono 10 frame. In ogni frame il giocatore ha due possibilità di abbattere 10 birilli
(pins). Il punteggio per il frame è il numero di birilli abbattuti, più i bonus per stike o
spare.
Uno spare è quando il giocatore abbatte 10 birilli in due tiri. Il bonus per quel frame è il
numero di birilli abbattuti al tiro successivo. Nel frame 3 dell'esempio, il punteggio è 10
(i birilli abbattuti) più il bonus di 5 (abbattuti nel tiro successivo.)
Uno strike è quando il giocatore abbatte tutti i birilli in un solo tiro. Il bonus per quel
frame è il numero di birilli abbattuti nei due tiri successivi
Nel decimo frame, se il giocatore fa uno strike o spare può fare i tiri necessari per
completare il frame. In ogni caso, al decimo frame non vengono fatti più di tre tiri.
26. I requisiti
• Scrivete una classe“Game” con due metodi:
• roll(pins : int) è chiamato ogni volta che il
giocatore fa un tiro. L’argomento è il
numero di birilli abbattuti.
• score(): int è chiamato quando il gioco
termina e ritorna il punteggio finale.
30. Una veloce sessione di design
Il decimo frame è diverso dagli
altri: può avere due o tre tiri.
31. Una veloce sessione di design
La funzione score
deve iterare su tutti i
frames e calcolare i
loro punteggi.
32. Una veloce sessione di design
Il punteggio di uno spare o di uno strike
dipende dal punteggio del frame
successivo
33. Coding Katas: String
Calculator
by Roy Osherove
(http://osherove.com/tdd-
kata-1)
34. StringCalculator Kata
Create a simple String calculator with a method
int Add(string numbers)
The method can take zero, one or two numbers, and
will return their sum
• for example “” or “1” or “1,2”
• for an empty string it will return 0
Start with the simplest test case of an empty string and
move to one and two numbers
35. StringCalculator Kata
Remember to solve things as simply as possible so
that you force yourself to write tests you did not
think about
Remember to refactor after each passing test
37. StringCalculator Kata
Allow the Add method to handle new lines between
numbers (instead of commas).
• the following input is ok: “1n2,3” (will equal
6)
• the following input is NOT ok: “1,n” (not need
to prove it - just clarifying)
38. StringCalculator Kata
Support different delimiters
to change a delimiter, the beginning of the string will contain a
separate line that looks like this:
“//[delimiter]n[numbers…]”
for example “//;n1;2” should return three where the default
delimiter is ‘;’ .
the first line is optional.
all existing scenarios should still be supported
39. StringCalculator Kata
Calling Add with a negative number will throw an
exception “negatives not allowed” - and the
negative that was passed.
If there are multiple negatives, show all of them in
the exception message
41. More on code kata
• http://codekata.pragprog.com/
• http://codingdojo.org/
• https://sites.google.com/site/tddproblems/all-problems-1
• http://xp123.com/articles/tests-from-a-hat/
42. Homework
Roman Numerals kata:
write a Roman class which converts an integer into a
roman number string.
es: 12 => “XII”
Bonus: can you write the inverse converter (from roman
to integer)?
es: “IX” => 9
45. Copyright 2008-2012
XPeppers
Tutti i diritti di riproduzione sono riservati.
Notas do Editor
\n
\n
\n
\n
\n
\n
\n
Quickly add a test.\nRun all tests and see the new one fail.\nMake a little change.\nRun all tests and see them all succeed.\nRefactor to remove duplication.\n\n
\n
First we'll solve the “that works” part\n Then we'll solve the “clean code” part\n
\n
\n
\n
\n
Esempio:\n \n Roman 0 => ""\n \n Mercato Titoli\n il mercato è chiuso di default\n non ci sono ordini su un titolo che non esiste\n se metto ordini su un titolo con il mercato chiuso ho una eccezione\n\n
\n
\n
Il prossimo test\n Trattiamo ogni test come una nuova occasione per imparare e ridurre la complessità sul modello del problema \n ogni test ci da ulteriore conoscenza\n ES\n Mercato Titoli\n qual'è la prossima domanda a cui vogliamo rispondere?\n\n
Il prossimo test\n Trattiamo ogni test come una nuova occasione per imparare e ridurre la complessità sul modello del problema \n ogni test ci da ulteriore conoscenza\n ES\n Mercato Titoli\n qual'è la prossima domanda a cui vogliamo rispondere?\n\n