160 likes | 292 Views
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
E N D
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)
Refactoring Techniques • Extract method • Extract constant • Introduce Explaining variable • Replace constructor with factory
Fig. 21.2 public class Player { private Piece piece; private Board board; private Die[] 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 piece; private Board board; private Die[] 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 ) ); }
Summary • TDD requires some paractice, but it can be powerful • Refactoring is a good approach to clean up!