Test Driven Development
Test Driven Developme
nt
Technique to design and develop software.
Practice part of the Extreme Programming methodology — XP
Based on three fundamental pillars.
The Three Pillars
Implement the exact functionality of the software.
Reduce the number of defects on the software – good quality software
Produce modular and highly reusable software.
When Doing TDD
It’s not about just writing tests.
Translate use cases to examples. Enough to describe the functionality without ambiguity.
Architecture will eventually emerge.
The TDD Algorithm
Red
GreenRefactor
The TDD Algorithm
Red
GreenRefactor
TDD In ActionWith an example ;-)
The Problem
Email validation mechanism
The Problem
Email validation mechanism
?
The Problem
Email validation mechanism
Neither empty nor null.
Has to contain an @ symbol
Has to belong to the .com, .net and .edu TDLs
Domain part can’t be 1 character long
All lowercase
Not contain numbers
Only _ . - symbols
Before we begin
Writing Tests
Testing framework Part of the language
Ruby Rust Go Python
External tools and libraries
Neither empty nor null
Red@Testpublic void shouldReturnFalseIfEmailIsNull() { String email = null; EmailValidator validator = new EmailValidator();
boolean isValid = validator.isValid(email);
assertThat(isValid, equalTo(false));}
Neither empty nor null
Green public boolean isValid(String email) { return false;}
Neither empty nor null
Red
@Testpublic void shouldReturnTrueIfEmailLengthIsGreaterThanZero() { String email = "[email protected]"; EmailValidator validator = new EmailValidator();
boolean isValid = validator.isValid(email);
assertThat(isValid, equalTo(true));}
Neither empty nor null
Greenpublic boolean isValid(String email) { if (email == null) { return false; } return email.length() > 0;}
Contains an @ symbol
Red
@Testpublic void shouldReturnFalseIfEmailDoesntContainAtSymbol () { String email = "someemail.com"; EmailValidator validator = new EmailValidator();
boolean isValid = validator.isValid(email);
assertThat(isValid, equalTo(false));}
Neither empty nor null
Greenpublic boolean isValid(String email) { if (email == null) { return false; } if (!email.contains("@")) { return false; } return email.length() > 0;}
Refactorprivate EmailValidator validator;
@Beforepublic void setUp () { validator = new EmailValidator();}
In the end… Components will behave exactly as we want.
Tests will be the documentation of our system.
Tests will break if changes compromise the system.