Chapter 1

Chapter 21
Test Driven development
TDD
• Write the test first
• Show that test fails
• Write code to pass the test
• Run whole suite of tests!
• This is unit testing
Why?
•
•
•
•
•
Testing gets done!
Programmer satisfaction
Clarification of interface and behavior
Provable repeatable verification
Confidence to change things
Warning
• NO such thing as a complete and perfect
test (No free lunch!)
jUnit
•
•
•
•
•
•
Many ide’s support jUnit testing
Requires adding library
Books shows jUnit 3
jUnit version 4:
@org.junit.Test – method annotation
Assert methods:
– assertEquals(“msg”,param1,param2)
Fig. 21.1
Refactoring Techniques
•
•
•
•
Extract method
Extract constant
Introduce Explaining variable
Replace constructor with factory
Fig. 21.2
public class Player
{
private Piece
private Board
private Die[]
// …
piece;
board;
dice;
public void takeTurn()
{
// roll dice
int rollTotal = 0;
for (int i = 0; i < dice.length; i++)
{
dice[i].roll();
rollTotal += dice[i].getFaceValue();
}
Square newLoc = board.getSquare(piece.getLocation(), rollTotal);
piece.setLocation(newLoc);
}
} // end of class
Fig. 21.3 Extract Method
public class Player
{
private Piece
private Board
private Die[]
// …
piece;
board;
dice;
public void takeTurn()
{
// the refactored helper method
int rollTotal = rollDice();
Square newLoc = board.getSquare(piece.getLocation(), rollTotal);
piece.setLocation(newLoc);
}
private int rollDice()
{
int rollTotal = 0;
for (int i = 0; i < dice.length; i++)
{
dice[i].roll();
rollTotal += dice[i].getFaceValue();
}
return rollTotal;
}
} // end of class
Fig. 21.4
// good method name, but the logic of the body is not clear
boolean isLeapYear( int year )
{
return
( ( ( year % 400 ) == 0 ) ||
( ( ( year % 4 ) == 0 ) && ( ( year % 100 ) != 0 ) ) );
}
Fig. 21.5
// that’s better!
boolean isLeapYear( int year )
{
boolean isFourthYear = ( ( year % 4 ) == 0 );
boolean isHundrethYear = ( ( year % 100 ) == 0);
boolean is4HundrethYear = ( ( year % 400 ) == 0);
return (
is4HundrethYear
|| ( isFourthYear && ! isHundrethYear ) );
}
Fig. 21.6
Fig. 21.7
Summary
• TDD requires some paractice, but it can
be powerful
• Refactoring is a good approach to clean
up!