SlideShare uma empresa Scribd logo
1 de 59
Getting Started with TDD
Ferdous Mahmud Shaon
Managing Director
Cefalo Bangladesh Ltd.
TDD stands for…
T D D
Development
Driven
Test
Old School Development Approach
Design Development Test
New School Development Approach
Design DevelopmentTest
Test Driven Development
“Test Driven Development (TDD) is a technique
for building software that guides software
development by writing tests.”
- Martin Fowler (Chief Scientist, ThoughtWorks)
• TDD is NOT primarily about testing or
development.
• It is rather about software design, where
design is evolved through testing and
refactoring.
TDD starts with Unit Testing
• In TDD, testing means Unit Testing
• Unit Testing is a testing technique
by which individual units or
components of a software are
tested programmatically.
• Unit is the smallest testable part of any software.
• In OOP, smallest unit is a method of a class.
• Who is responsible for writing Unit Tests?
– Testers Developers
So I need to write
codes to test my
code !!!???
But I learnt only
writing codes, but
not testing it!
Unit Testing Tools
Unit Testing with JUnit
• JUnit is a popular unit testing framework for Java.
• Unit Tests are written like ordinary source codes.
• Source codes and corresponding unit tests are kept
under same package name but in different directories.
Installing JUnit 5
Gradle
Maven
JUnit Methods
• Annotations are used to mark a method as
test method.
• Some helper methods might be needed to be
executed before and/or after running a test
method.
• All these methods must return “void” and
take no parameters.
• A test method must have at least one
Assertion in it.
JUnit5 Assert Methods
Assert Method Description
assertEquals()
assertNotEquals()
Invokes the equals() methods on the arguments to check
whether they are equal.
assertSame()
assertNotSame()
Uses == on the arguments to check whether they are equal
assertTrue()
assertFalse()
Checks if the given boolean argument evaluates to true or false
assertNull()
assertNotNull()
Checks if the given argument is null or NOT null
assertArrayEquals()
Checks if the given array arguments passed have same elements
in the same order
assertThrows()
Checks if the given code block throws an Exception and the type
of the Exception matches with the given type.
These methods are used in unit test methods for comparing expected and
actual result. They are static methods in org.junit.jupiter.api.Assertions class.
JUnit5 Annotations
Annotation Description
@Test
It is used to mark a method as a JUnit test.
Referring to org.junit.jupiter.api.Test
@BeforeEach
The annotated method will be run before each test method in the
test class. Referring to org.junit.jupiter.api.BeforeEach
@AfterEach
The annotated method will be run after each test method in the test
class. Referring to org.junit.jupiter.api.AfterEach
@BeforeAll
The annotated method will be run before all test methods in the
test class. This method must be static.
Referring to org.junit.jupiter.api.BeforeAll
@AfterAll
The annotated method will be run after all test methods in the test
class. This method must be static.
Referring to org.junit.jupiter.api.AfterAll
Unit Test Example with JUnit5
Unit Tests Best Practices
• Unit test cases should be independent. In case of any
enhancements or change in requirements, unit test cases
should not be affected.
• Follow clear and consistent naming conventions for your unit
tests. Test name should reflect the intent/purpose of the test.
• In case of a change in code in any module, ensure there is a
corresponding unit test case for the module, and the module
passes the tests before changing the implementation.
• Bugs identified during unit testing must be fixed before
proceeding to the next phase in SDLC
• Adopt a "test as your code" approach. The more code you write
without testing, the more paths you have to check for errors.
Guidelines for writing Unit Tests
A test is not a Unit Test if:
– It connects with the database
– It communicates across the network
– It touches the file system
– It can’t run at the same time as any of your other
unit tests
– You have to do special things to your environment
(such as editing config files) to run it.
— Michael Feathers,
A Set Of Unit Testing Rules (2005)
Test Doubles
• Unit test should test functionality in isolation.
• Side effects from other classes or the system
should be eliminated for a unit test, if
possible.
• This can be done via using test replacements
(test doubles) for the real dependencies.
• Test double is an object that can stand in for a
real object in a test, similar to how a stunt
double stands in for an actor in a movie.
Test Doubles
Common Excuses against Unit Tests
• I am paid to write code, not tests!
• I am a developer, not tester - so I’m not responsible
for writing tests!
• We already have testers - why do we need unit tests?
• We are working on a tight deadline - where do I have
time for writing unit tests?
• I don’t know how to write unit tests
• Ours is legacy code - can’t write unit tests for them
• If I touch the code, it may break!
Myths lead to a Vicious Cycle
"Never in the field of
software engineering has so
much been owed by so many
to so few lines of code.”
– Martin Fowler on Unit Testing
But I already write unit tests!
• Just because, you write unit tests, doesn’t
mean you follow TDD!
• Unit tests are often written after development
(coding implementation)
– That is called Plain Old Unit testing (POUting)
• However in TDD approach,
Unit tests must be written first before
development (coding implementation)
Unit testing after code: Disadvantages
• Testing does not give direct feedback to design
and programming
– But in TDD, the feedback is directly fed back into
improving design and programs
• Most often, after implementing the functionality
in code, unit testing is omitted.
– TDD inverts this sequence and ensure all components
have unit tests first before implementation
• Writing tests after developing code often results
in “happy path” testing only!
Why Test First Approach?
Why Test First Approach?
Test Driven Development Cycle
Step 1: Write test that fails
Red—write a little test that doesn’t work, perhaps
doesn’t even compile at first!
Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
Step 2: Get code working to pass test
Green — write minimal amount of code to make
the test work, committing whatever sins
necessary in the process.
Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
Step 3: Cleanup and Refactor
• Refactor — eliminate all duplications and code
smells, which may have been introduced while
getting the test to pass in Step 2.
Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
TDD Mantra
TDD in action
Let’s Build a Simple Calculator
• We will try to implement a simple calculator by
applying TDD approach
• Let’s keep the requirements very simple.
• Our simple calculator will cover only 2 functions:
– Addition of 2 given numbers
• Input 2 numbers
• Returns the sum of the 2 numbers
– Division of one number by another number
• Input 2 numbers – dividend and divisor
• Returns the quotient of the 2 numbers
• Note, divisor cannot be zero
TDD in action
SimpleCalculator Class
– Let’s start with an empty class
– We’ll gradually build up this through TDD
TDD in action
Test1: write a testcase for adding 2 numbers
– input any 2 numbers
– expect to have the sum of them
TDD in action
But our test for addition fails!
Error:
TDD in action
In SimpleCalculator class, we’ll write bear
minimum amount of code to
– fix the error by introducing add() method
– Pass the test for adding 2 numbers
• Change it until we make it RED to GREEN!
TDD in action
Test2: write a testcase for division of 2 numbers
– input 2 numbers: dividend and divisor
– expect to have the quotient
TDD in action
But our test for division also fails!
Error:
TDD in action
In SimpleCalculator class, we’ll write bear
minimum amount of code to
– fix the error by introducing divide() method
– Pass the test for division of 2 numbers
– The goal is to pass the failing test somehow.
TDD in action
Refactor
• Look for any code smells, duplicates in main and test
class and refactor them.
• Make sure, the test result doesn’t get affected!
TDD in action
Refactor the Code Smells
TDD in action
Test3: write a testcase for division with 0 as divisor
– input any number as dividend and 0 as divisor
– Let’s expect to have IllegalArgumentException
TDD in action
But our 0 divisor test fails!
Error:
TDD in action
Now, we’ll just need to throw
IllegalArgumentException, if divisor is 0.
This small change is enough to pass the test.
3 Laws of TDD
Uncle Bob’s First law of Testto Dynamics:
You may not write production code unless
you’ve first written a failing unit test.
3 Laws of TDD (cont.)
Uncle Bob’s Second law of Testto Dynamics:
You may not write any more of a unit test
than is sufficient to fail.
3 Laws of TDD (cont.)
Uncle Bob’s Third law of Testto Dynamics:
You may not write more production code than is
sufficient to make the failing unit test pass.
Summarize Uncle Bob’s rules for TDD
• Start with a small unit test, that fails
• Write bare minimum code to make the failing
test pass
• Refactor the code smells without affecting
functionality and test result
• Continue the above 3 steps until you have
any failing unit tests
Benefits of TDD
Cleaner Code Testable SOLID Code
Self-documenting Unit Tests
Increased Quality,
Reduced Bugs
Maintainable and
Extensible Code
Happy-path and
Unhappy path Testing
Safer Refactoring Faster Debugging
When not to use TDD?
• Developers must be experienced in writing
tests before implementing TDD.
• More suited for implementing complex
business logic, back-end systems etc.
• Can be overhead for very simple projects.
• Not suitable for UI development.
• Can backfire when the environment is not
suitable or it is used incorrectly.
Does TDD guarantee Good Code?
“TDD helps with, but does not guarantee,
good design & good code.
Skill, talent, and expertise remain necessary.”
— Esko Luontola
TDD slows down Development?
“I can write code a lot faster
if it doesn’t have to work!”
– Kent Beck
Follow the straight path!
Recommended Reading
Test Driven Development: By Example, by Kent Beck
Must read on TDD
by its originator
Kent Beck
Recommended Reading
Refactoring: Improving the Design of Existing Code, by Martin Fowler
Covers refactoring
of code smells by
design principles
& best practices!
Useful Links
• GitHub Repository
https://github.com/Cefalo/lets-learn-tdd
• https://www.freecodecamp.org/news/test-driven-
development-what-it-is-and-what-it-is-not-41fa6bca02a2/
• https://hackernoon.com/introduction-to-test-driven-
development-tdd-61a13bc92d92
• https://www.guru99.com/test-driven-development.html
• http://agiledata.org/essays/tdd.html
Thank You!
Question & Answers
?

Mais conteúdo relacionado

Mais procurados

Introduction to BDD
Introduction to BDDIntroduction to BDD
Introduction to BDDKnoldus Inc.
 
Code Review Best Practices
Code Review Best PracticesCode Review Best Practices
Code Review Best PracticesTrisha Gee
 
BDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVABDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVASrinivas Katakam
 
What is sanity testing
What is sanity testingWhat is sanity testing
What is sanity testingpooja deshmukh
 
RESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsRESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsQASymphony
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentNaresh Jain
 
Using Postman to Automate API On-Boarding
Using Postman to Automate API On-BoardingUsing Postman to Automate API On-Boarding
Using Postman to Automate API On-BoardingPostman
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010guest5639fa9
 
ISTQB - Software development life cycle
ISTQB - Software development life cycleISTQB - Software development life cycle
ISTQB - Software development life cycleHoangThiHien1
 
Introducing BDD and TDD with Cucumber
Introducing BDD and TDD with CucumberIntroducing BDD and TDD with Cucumber
Introducing BDD and TDD with CucumberKnoldus Inc.
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefAhmed Shreef
 
Automation test framework with cucumber – BDD
Automation test framework with cucumber – BDDAutomation test framework with cucumber – BDD
Automation test framework with cucumber – BDD123abcda
 
Testing strategy for agile projects updated
Testing strategy for agile projects updatedTesting strategy for agile projects updated
Testing strategy for agile projects updatedTharinda Liyanage
 

Mais procurados (20)

Introduction to BDD
Introduction to BDDIntroduction to BDD
Introduction to BDD
 
Code Review Best Practices
Code Review Best PracticesCode Review Best Practices
Code Review Best Practices
 
BDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVABDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVA
 
Jenkins CI
Jenkins CIJenkins CI
Jenkins CI
 
Cucumber BDD
Cucumber BDDCucumber BDD
Cucumber BDD
 
What is sanity testing
What is sanity testingWhat is sanity testing
What is sanity testing
 
RESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and JenkinsRESTful API Testing using Postman, Newman, and Jenkins
RESTful API Testing using Postman, Newman, and Jenkins
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Tdd and bdd
Tdd and bddTdd and bdd
Tdd and bdd
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Using Postman to Automate API On-Boarding
Using Postman to Automate API On-BoardingUsing Postman to Automate API On-Boarding
Using Postman to Automate API On-Boarding
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
ISTQB - Software development life cycle
ISTQB - Software development life cycleISTQB - Software development life cycle
ISTQB - Software development life cycle
 
Continuous testing
Continuous testing Continuous testing
Continuous testing
 
Introducing BDD and TDD with Cucumber
Introducing BDD and TDD with CucumberIntroducing BDD and TDD with Cucumber
Introducing BDD and TDD with Cucumber
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
Automation test framework with cucumber – BDD
Automation test framework with cucumber – BDDAutomation test framework with cucumber – BDD
Automation test framework with cucumber – BDD
 
Testing strategy for agile projects updated
Testing strategy for agile projects updatedTesting strategy for agile projects updated
Testing strategy for agile projects updated
 

Semelhante a Getting started with Test Driven Development

An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingSahar Nofal
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptxmianshafa
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1Blue Elephant Consulting
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentHendrik Neumann
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Abhijeet Vaikar
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017Xavi Hidalgo
 

Semelhante a Getting started with Test Driven Development (20)

An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
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
 
TDD talk
TDD talkTDD talk
TDD talk
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptx
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)Unit testing (Exploring the other side as a tester)
Unit testing (Exploring the other side as a tester)
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit Testing talk
Unit Testing talkUnit Testing talk
Unit Testing talk
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Mais de Ferdous Mahmud Shaon

Tips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering CareerTips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering CareerFerdous Mahmud Shaon
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously Ferdous Mahmud Shaon
 
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() methodFerdous Mahmud Shaon
 

Mais de Ferdous Mahmud Shaon (6)

Tips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering CareerTips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering Career
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSS
 
Business Communcation
Business CommuncationBusiness Communcation
Business Communcation
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciouslyEffective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
 
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() method
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 

Último

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 

Último (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 

Getting started with Test Driven Development

  • 1. Getting Started with TDD Ferdous Mahmud Shaon Managing Director Cefalo Bangladesh Ltd.
  • 2.
  • 3. TDD stands for… T D D Development Driven Test
  • 4. Old School Development Approach Design Development Test
  • 5. New School Development Approach Design DevelopmentTest
  • 6. Test Driven Development “Test Driven Development (TDD) is a technique for building software that guides software development by writing tests.” - Martin Fowler (Chief Scientist, ThoughtWorks) • TDD is NOT primarily about testing or development. • It is rather about software design, where design is evolved through testing and refactoring.
  • 7. TDD starts with Unit Testing • In TDD, testing means Unit Testing • Unit Testing is a testing technique by which individual units or components of a software are tested programmatically. • Unit is the smallest testable part of any software. • In OOP, smallest unit is a method of a class. • Who is responsible for writing Unit Tests? – Testers Developers
  • 8. So I need to write codes to test my code !!!??? But I learnt only writing codes, but not testing it!
  • 10. Unit Testing with JUnit • JUnit is a popular unit testing framework for Java. • Unit Tests are written like ordinary source codes. • Source codes and corresponding unit tests are kept under same package name but in different directories.
  • 12. JUnit Methods • Annotations are used to mark a method as test method. • Some helper methods might be needed to be executed before and/or after running a test method. • All these methods must return “void” and take no parameters. • A test method must have at least one Assertion in it.
  • 13. JUnit5 Assert Methods Assert Method Description assertEquals() assertNotEquals() Invokes the equals() methods on the arguments to check whether they are equal. assertSame() assertNotSame() Uses == on the arguments to check whether they are equal assertTrue() assertFalse() Checks if the given boolean argument evaluates to true or false assertNull() assertNotNull() Checks if the given argument is null or NOT null assertArrayEquals() Checks if the given array arguments passed have same elements in the same order assertThrows() Checks if the given code block throws an Exception and the type of the Exception matches with the given type. These methods are used in unit test methods for comparing expected and actual result. They are static methods in org.junit.jupiter.api.Assertions class.
  • 14. JUnit5 Annotations Annotation Description @Test It is used to mark a method as a JUnit test. Referring to org.junit.jupiter.api.Test @BeforeEach The annotated method will be run before each test method in the test class. Referring to org.junit.jupiter.api.BeforeEach @AfterEach The annotated method will be run after each test method in the test class. Referring to org.junit.jupiter.api.AfterEach @BeforeAll The annotated method will be run before all test methods in the test class. This method must be static. Referring to org.junit.jupiter.api.BeforeAll @AfterAll The annotated method will be run after all test methods in the test class. This method must be static. Referring to org.junit.jupiter.api.AfterAll
  • 15. Unit Test Example with JUnit5
  • 16. Unit Tests Best Practices • Unit test cases should be independent. In case of any enhancements or change in requirements, unit test cases should not be affected. • Follow clear and consistent naming conventions for your unit tests. Test name should reflect the intent/purpose of the test. • In case of a change in code in any module, ensure there is a corresponding unit test case for the module, and the module passes the tests before changing the implementation. • Bugs identified during unit testing must be fixed before proceeding to the next phase in SDLC • Adopt a "test as your code" approach. The more code you write without testing, the more paths you have to check for errors.
  • 17. Guidelines for writing Unit Tests A test is not a Unit Test if: – It connects with the database – It communicates across the network – It touches the file system – It can’t run at the same time as any of your other unit tests – You have to do special things to your environment (such as editing config files) to run it. — Michael Feathers, A Set Of Unit Testing Rules (2005)
  • 18. Test Doubles • Unit test should test functionality in isolation. • Side effects from other classes or the system should be eliminated for a unit test, if possible. • This can be done via using test replacements (test doubles) for the real dependencies. • Test double is an object that can stand in for a real object in a test, similar to how a stunt double stands in for an actor in a movie.
  • 20. Common Excuses against Unit Tests • I am paid to write code, not tests! • I am a developer, not tester - so I’m not responsible for writing tests! • We already have testers - why do we need unit tests? • We are working on a tight deadline - where do I have time for writing unit tests? • I don’t know how to write unit tests • Ours is legacy code - can’t write unit tests for them • If I touch the code, it may break!
  • 21. Myths lead to a Vicious Cycle
  • 22. "Never in the field of software engineering has so much been owed by so many to so few lines of code.” – Martin Fowler on Unit Testing
  • 23. But I already write unit tests! • Just because, you write unit tests, doesn’t mean you follow TDD! • Unit tests are often written after development (coding implementation) – That is called Plain Old Unit testing (POUting) • However in TDD approach, Unit tests must be written first before development (coding implementation)
  • 24. Unit testing after code: Disadvantages • Testing does not give direct feedback to design and programming – But in TDD, the feedback is directly fed back into improving design and programs • Most often, after implementing the functionality in code, unit testing is omitted. – TDD inverts this sequence and ensure all components have unit tests first before implementation • Writing tests after developing code often results in “happy path” testing only!
  • 25. Why Test First Approach?
  • 26. Why Test First Approach?
  • 28. Step 1: Write test that fails Red—write a little test that doesn’t work, perhaps doesn’t even compile at first! Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
  • 29. Step 2: Get code working to pass test Green — write minimal amount of code to make the test work, committing whatever sins necessary in the process. Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
  • 30. Step 3: Cleanup and Refactor • Refactor — eliminate all duplications and code smells, which may have been introduced while getting the test to pass in Step 2. Source: Test Driven Development: By Example, Kent Beck, 240 pages, Addison-Wesley Professional, 2002
  • 33. Let’s Build a Simple Calculator • We will try to implement a simple calculator by applying TDD approach • Let’s keep the requirements very simple. • Our simple calculator will cover only 2 functions: – Addition of 2 given numbers • Input 2 numbers • Returns the sum of the 2 numbers – Division of one number by another number • Input 2 numbers – dividend and divisor • Returns the quotient of the 2 numbers • Note, divisor cannot be zero
  • 34. TDD in action SimpleCalculator Class – Let’s start with an empty class – We’ll gradually build up this through TDD
  • 35. TDD in action Test1: write a testcase for adding 2 numbers – input any 2 numbers – expect to have the sum of them
  • 36. TDD in action But our test for addition fails! Error:
  • 37. TDD in action In SimpleCalculator class, we’ll write bear minimum amount of code to – fix the error by introducing add() method – Pass the test for adding 2 numbers • Change it until we make it RED to GREEN!
  • 38. TDD in action Test2: write a testcase for division of 2 numbers – input 2 numbers: dividend and divisor – expect to have the quotient
  • 39. TDD in action But our test for division also fails! Error:
  • 40. TDD in action In SimpleCalculator class, we’ll write bear minimum amount of code to – fix the error by introducing divide() method – Pass the test for division of 2 numbers – The goal is to pass the failing test somehow.
  • 41. TDD in action Refactor • Look for any code smells, duplicates in main and test class and refactor them. • Make sure, the test result doesn’t get affected!
  • 42. TDD in action Refactor the Code Smells
  • 43. TDD in action Test3: write a testcase for division with 0 as divisor – input any number as dividend and 0 as divisor – Let’s expect to have IllegalArgumentException
  • 44. TDD in action But our 0 divisor test fails! Error:
  • 45. TDD in action Now, we’ll just need to throw IllegalArgumentException, if divisor is 0. This small change is enough to pass the test.
  • 46. 3 Laws of TDD Uncle Bob’s First law of Testto Dynamics: You may not write production code unless you’ve first written a failing unit test.
  • 47. 3 Laws of TDD (cont.) Uncle Bob’s Second law of Testto Dynamics: You may not write any more of a unit test than is sufficient to fail.
  • 48. 3 Laws of TDD (cont.) Uncle Bob’s Third law of Testto Dynamics: You may not write more production code than is sufficient to make the failing unit test pass.
  • 49. Summarize Uncle Bob’s rules for TDD • Start with a small unit test, that fails • Write bare minimum code to make the failing test pass • Refactor the code smells without affecting functionality and test result • Continue the above 3 steps until you have any failing unit tests
  • 50. Benefits of TDD Cleaner Code Testable SOLID Code Self-documenting Unit Tests Increased Quality, Reduced Bugs Maintainable and Extensible Code Happy-path and Unhappy path Testing Safer Refactoring Faster Debugging
  • 51. When not to use TDD? • Developers must be experienced in writing tests before implementing TDD. • More suited for implementing complex business logic, back-end systems etc. • Can be overhead for very simple projects. • Not suitable for UI development. • Can backfire when the environment is not suitable or it is used incorrectly.
  • 52. Does TDD guarantee Good Code? “TDD helps with, but does not guarantee, good design & good code. Skill, talent, and expertise remain necessary.” — Esko Luontola
  • 53. TDD slows down Development? “I can write code a lot faster if it doesn’t have to work!” – Kent Beck
  • 55. Recommended Reading Test Driven Development: By Example, by Kent Beck Must read on TDD by its originator Kent Beck
  • 56. Recommended Reading Refactoring: Improving the Design of Existing Code, by Martin Fowler Covers refactoring of code smells by design principles & best practices!
  • 57. Useful Links • GitHub Repository https://github.com/Cefalo/lets-learn-tdd • https://www.freecodecamp.org/news/test-driven- development-what-it-is-and-what-it-is-not-41fa6bca02a2/ • https://hackernoon.com/introduction-to-test-driven- development-tdd-61a13bc92d92 • https://www.guru99.com/test-driven-development.html • http://agiledata.org/essays/tdd.html