Presentation is loading. Please wait.

Presentation is loading. Please wait.

Test Driven development

Similar presentations


Presentation on theme: "Test Driven development"— Presentation transcript:

1 Test Driven development
Chapter 21 Test Driven development

2 Write code to pass the test Run whole suite of tests!
TDD Write the test first Show that test fails Write code to pass the test Run whole suite of tests! This is unit testing

3 Programmer satisfaction Clarification of interface and behavior
Why? Testing gets done! Programmer satisfaction Clarification of interface and behavior Provable repeatable verification Confidence to change things

4 NO such thing as a complete and perfect test (No free lunch!)
Warning NO such thing as a complete and perfect test (No free lunch!)

5 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)

6 Fig. 21.1

7 Four listed in the test: Extract method Extract constant
Refactoring Four listed in the test: Extract method Extract constant Introduce Explaining variable Replacer constructor with factory

8 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

9 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

10 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 ) ) ); }

11 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 ) ); }

12 Fig. 21.6

13 Fig. 21.7

14 TDD requires some paractice, but it can be powerful
Summary TDD requires some paractice, but it can be powerful Refactoring is a good approach to clean up!


Download ppt "Test Driven development"

Similar presentations


Ads by Google