Test Driven Development is nothing more than "Unit Testing" but an art of unit testing. Arts require lots of practice.
To start with TDD, it is very important to understand what is unit testing. The common problem many coders have is "Not understanding what is a unit". This presentation targets to solve this basic problem than going behind non-understandable jargons.
Test Driven Development - The art of fearless programming
1. TDD
The Art of Fearless Programming
On 06/23/2016 @ SLASSCOM Quality Forum
BY CHAMIL JEEWANTHA
SOFTWARE ARCHITECT AT ZONE24X7
ALL RIGHTS RESERVED
2. What Will You Take Back?
Test Driven Development
Answers for What? Why? Who? When? & Where?
Better understanding of a ”Unit”?
The difference between,
Unit Test, Integration Test, Test First Development, ATDD
Your belongings ;)
3. Some Groundwork
Ask questions
Art vs Science
Arts require lots of practice
Arts do not require to be proven
Overlaps may occur
Most of the points are subjective
E.g. Drinking water is good (in general, not always)
5. Some Core Values
Quality is everyone’s responsibility
Good test coverage is important
Line coverage != test coverage
Early testing is better
More test cycles are better
Architecture plays a big role in Maintainability
Maintainability is a significant Quality aspect (Specially with Agile)
6. What is Unit Testing?
A single, indivisible entity
The smallest testable part of an application
End User Entire software
QA Engineer Single Functionality
Architect A Module, Component
Developer A Class (OOP), Function (FP)
7. Class? Why not Method (OOP)?
IF
A class follows the “Single Responsibility Principle”
AND
The methods are cohesive
THEN
Really hard to use a method independently
8. A Unit for a Politician
Source: https://en.wikipedia.org/wiki/William_Bennett
9. “
”
If we have stronger families we will
have stronger schools and stronger
communities with less poverty and less
crime.
WILLIAM BENNETT, A FORMER UNITED STATES SECRETARY OF EDUCATION
http://www.nytimes.com/roomfordebate/2012/04/24/are-
family-values-outdated/stronger-families-stronger-societies
10. “
”
If we have stronger Units we will have
stronger Modules and stronger
Software with Rich Features and less
Bugs.
CHAMIL JEEWANTHA, SOFTWARE ARCHITECT @ ZONE24X7
TDD (The Art of Fearless Programming) - SLASSCOM Quality
Forum
11. Example of a Unit
public class AndCriteria implements Criteria{
private final Criteria criteria1;
private final Criteria criteria2;
public AndCriteria(Criteria criteria1, Criteria criteria2) {
this.criteria1 = criteria1;
this.criteria2 = criteria2;
}
public List filter(List values) {
List filteredList = criteria1.filter(values);
return criteria2.filter(filteredList);
}
}
12. Characteristics of a Good Unit
Not so lengthy
Self explained
Used by its clients via an interface
SOLID
Well Tested
Compliant with Best Practices (All above + many
more)
13. Unit Test
Select the smallest piece of testable software in the
application
Isolate it from the rest of the code
Determine whether it behaves exactly as you expect
Each unit is tested separately before integrating them into
modules to test the interfaces between modules
Ref: https://msdn.microsoft.com/en-
us/library/aa292197(VS.71).aspx
14. Characteristics of a Good Unit Test
Automated
Thorough
Repeatable
Independent
Test only one thing
Should not rely on each other
Fast
Professional (Readable, Maintainable, Trustworthy)
15. Isolating a Unit for Testing
Is this Site
Manager good?
Site Manager
He should by
cement from the
shop named by me
17. How to Test
Create a dummy bag of cement
Create a dummy hardware shop
Instruct the dummy hardware to send the dummy bag of
cement if somebody asks for a bag of cement.
Give the address of dummy hardware to the site manager.
Ask for a bag of cement from the site manager
Verify whether he has called the given hardware
Verify whether we receive the dummy cement bag back.
19. Example: Requirement of
AndCriteria
The AndCriteria should be an implementation of
Criteria
Should filter a given list by first expression and return
a filteredList
Should filter the filteredList by the second expression
and return the finalList
20. Example: Tests for AndCriteria
1. Should_FilterThrough1StAnd2ndExpressions_When_ALi
stIsGiven
2. Should_ThrowException_When_NullIsProvided
21. Example: AndCriteria : Test 1
@Test
public void Should_FilterThrough1StAnd2ndExpressions_When_AListIsGiven(){
List input = // dummy list
List lst1 = // dummy list
List lst2 = // dummy list
Criteria expr1 = // dummy criteria -> filter(input) returns dummy list (lst1)
Criteria expr2 = // dummy criteria -> filter(lst1) returns dummy list (lst2)
AndCriteria criteria = new AndCriteria(expr1, expr2);
List output = criteria.filter(input);
assertThat(output, is(lst2));
}
22. Example: AndCriteria : Test 2
@Test (expected = IllegalArgumentException.class)
public void Should_ThrowException_When_NullIsProvided() {
List input = null
AndCriteria criteria = new AndCriteria(expr1, expr2);
criteria.filter(input);
}
23. Example 2: Evaluate Expression
The user should provide an expression with relevant
value mappings to its variables.
Java Evaluate ((a+b)*3)-2 a=5 b=8
The program should assign a & b values to this
expression and evaluate it.
24. Code for Evaluating an Expression
class Evaluate{
public static void main(String[] args){
String expr = ... // assign variables with values
// evaluate the expr
double value = // the output value of the evaluation
System.out.println(value);
}
}
Can you write a
“Good” automated
test?
25. Common Complaints About Unit
Testing
Deadline is near, no time to write tests
Writing tests takes longer than the production code
Hard to keep the test suite up to date
One line of code change breaks 100s of tests
The code
works. But
very hard to
write unit
tests
So, Refactor
your code
Not Hard,
Impossible!
27. Rules: TFD
1. Write a(nother) unit test that fails
2. Write the minimum production code until all the tests
pass
3. Repeat until all your work is done.
Fail Pass
28. Test First Benefits (Vs Test Late)
All the benefits of Unit testing
+
Write non-testable codes are impossible
Test-first forces you to plan before you code
It’s faster than writing code without tests
It saves you from lengthy code
It guides you to build good, SOLID units
It increases your confidence (refactor without fear)
Acts as a real-time progress bar
29. “
”
TDD = TFD + Refactoring
REFACTOR YOUR CODE AT EVERY ITERATION
TDD = Test Driven Development
TFD = Test First Development
30. Rules: TDD
1. Write a(nother) unit test that fails
2. Write the minimum production code until all the
tests pass
3. Refactor your code
4. Repeat until all your work is done
Fail Pass
Refactor
32. Scenario
For a given Access log file of a web server
Client needs a command line utility to get
Percentage of success responses
Percentage of failure responses
Time Source Destination Response time Status
2016/04/22 12:15:05 PM 10.1.5.8 10.1.24.14 55 200
33. Approaching with TDD
A Class called “LogAnalyzer”
With method “analyze”
Writing the analyze method
Reading the file is not matching to this name
Separate LogReader should be used
LogReader.read should return List<Request>
Two Stats to be calculated
StatCalculator interface
List of StatCalculators should be injected to LogAnalyzer
34. Tools
IDE (IntelliJ)
Test Runner (Junit)
Mock libraries (Mockito)
Verification (Hamcrest)
36. ATDD vs TDD
TDD to drive the design
ATDD to make sure all the requirements are implemented
37. Additional time due to TDD?
Beginner
Lots of time thinking where to start
Experienced Developer
Initially 15 - 17% more
Big time saving later for both
Not having a proper understanding about what is a unit and what is not, matters a lot when solving the complaints comes with unit testing.
TDD is an Art
Lets talk about Unit first.
If your methods are independent from other parts of your class, it is a smell most of the times.
Computer science follows the common patterns & principles which are applicable in other domains.
Lets apply the same concept here.
Cohesion within the Members of the family is important.
Loose coupling with the other families also important (Tight coupling between mother of one family with the father of the other family leads many problems).
A strong family will have one vision.
If the site manager is working as I expected, he should follow the way I told to him as it is.
Monolithic code makes Unit Testing impossible
Proper naming will guide you to identify what your unit should really do.