SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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++Hong Le Van
 
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.Deepak Singhvi
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
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)Sung Kim
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 
Software Quality via Unit Testing
Software Quality via Unit TestingSoftware Quality via Unit Testing
Software Quality via Unit TestingShaun Abram
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentMireia Sangalo
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard 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 MistakesRoy Osherove
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
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 TechniquesSung Kim
 
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 ShaonCefalo
 

La actualidad más candente (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
 

Similar a Test Driven Development - The art of fearless programming

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 easierChristian Hujer
 
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.Mohamed Taman
 
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 + EclipseUTC Fire & Security
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
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 applicationsAhmad Kazemi
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
Software testing
Software testingSoftware testing
Software testingBala Ganesh
 

Similar a 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
 

Último

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Último (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

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

Notas del editor

  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.