Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 21 Test Driven development

2 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 Why? Testing gets done! Programmer satisfaction Clarification of interface and behavior Provable repeatable verification Confidence to change things

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

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

6 Fig. 21.1

7 Refactoring Techniques Extract method Extract constant Introduce Explaining variable Replace 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 Summary TDD requires some paractice, but it can be powerful Refactoring is a good approach to clean up!


Download ppt "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."

Similar presentations


Ads by Google