SlideShare une entreprise Scribd logo
1  sur  38
TDD
The Art of Fearless Programming
On 06/23/2016 @ SLASSCOM Quality Forum
BY CHAMIL JEEWANTHA
SOFTWARE ARCHITECT AT ZONE24X7
ALL RIGHTS RESERVED
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 ;)
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)
Pitch Report ARE WE ON THE SAME
PAGE?
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)
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)
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
A Unit for a Politician
Source: https://en.wikipedia.org/wiki/William_Bennett
“
”
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
“
”
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
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);
}
}
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)
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
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)
Isolating a Unit for Testing
Is this Site
Manager good?
Site Manager
He should by
cement from the
shop named by me
Test Flow
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.
In Java with Mockito
BagOfCement dummyCement = mock(BagOfCement.class);
HwShop dummyHw = mock(HwShop.class);
When(dummyHw.buyCement()).thenReturn(dummyCement);
siteManager.setHwShop(dummyHw);
BagOfCement output = siteManager.askCement();
assertThat(output, is(dummyCement));
verify(dummyHw).buyCement();
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
Example: Tests for AndCriteria
1. Should_FilterThrough1StAnd2ndExpressions_When_ALi
stIsGiven
2. Should_ThrowException_When_NullIsProvided
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));
}
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);
}
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.
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?
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!
Solution: (TFD)
Test First
Development
THE PARADIGM SHIFT
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
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
“
”
TDD = TFD + Refactoring
REFACTOR YOUR CODE AT EVERY ITERATION
TDD = Test Driven Development
TFD = Test First Development
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
DEMO GET YOUR HANDS DIRTY
WITH TDD
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
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
Tools
 IDE (IntelliJ)
 Test Runner (Junit)
 Mock libraries (Mockito)
 Verification (Hamcrest)
FAQ
ATDD vs TDD
 TDD to drive the design
 ATDD to make sure all the requirements are implemented
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
Thank You!
KDCHAMIL@GMAIL.COM

Contenu connexe

Tendances

Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
Alex Su
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove
 
A Survey on Automatic Software Evolution Techniques
A Survey on Automatic Software Evolution TechniquesA Survey on Automatic Software Evolution Techniques
A Survey on Automatic Software Evolution Techniques
Sung Kim
 

Tendances (20)

Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit test
Unit testUnit test
Unit test
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
Software Quality via Unit Testing
Software Quality via Unit TestingSoftware Quality via Unit Testing
Software Quality via Unit Testing
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
A Survey on Automatic Software Evolution Techniques
A Survey on Automatic Software Evolution TechniquesA Survey on Automatic Software Evolution Techniques
A Survey on Automatic Software Evolution Techniques
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
 

Similaire à Test Driven Development - The art of fearless programming

Software testing
Software testingSoftware testing
Software testing
Bala Ganesh
 

Similaire à Test Driven Development - The art of fearless programming (20)

2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
Implementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsImplementing TDD in for .net Core applications
Implementing TDD in for .net Core applications
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Unit testing
Unit testingUnit testing
Unit testing
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Testing
TestingTesting
Testing
 
Software testing
Software testingSoftware testing
Software testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Dernier (20)

Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

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)
  • 4. Pitch Report ARE WE ON THE SAME PAGE?
  • 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.
  • 18. In Java with Mockito BagOfCement dummyCement = mock(BagOfCement.class); HwShop dummyHw = mock(HwShop.class); When(dummyHw.buyCement()).thenReturn(dummyCement); siteManager.setHwShop(dummyHw); BagOfCement output = siteManager.askCement(); assertThat(output, is(dummyCement)); verify(dummyHw).buyCement();
  • 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
  • 31. DEMO GET YOUR HANDS DIRTY WITH TDD
  • 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)
  • 35. FAQ
  • 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

Notes de l'éditeur

  1. 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.
  2. TDD is an Art
  3. Lets talk about Unit first.
  4. If your methods are independent from other parts of your class, it is a smell most of the times.
  5. Computer science follows the common patterns & principles which are applicable in other domains.
  6. 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.
  7. If the site manager is working as I expected, he should follow the way I told to him as it is.
  8. Monolithic code makes Unit Testing impossible
  9. Proper naming will guide you to identify what your unit should really do.