SlideShare a Scribd company logo
1 of 27
Download to read offline
Test Driven
Development
“TDD  is  not  testing,  it  is  a  design  technique”.

Christoforos Nalmpantis
What is TDD
TDD is a style of development where:
• You maintain an exhaustive suite of Programmer Tests
• No code goes into production unless it has associated tests
• You write the tests first
• The tests determine what code you need to write
Red – Green - Refactor
1. Write a test that fails
RED

REFACTOR

3. Eliminate redundancy

GREEN

2. Make the code work
A sad misconception
Because of the name of TDD most inexperienced developers
believe it is testing. This leads to the following objections:
• Writing unit tests takes too much time.
• How  could  I  write  tests  first  if  I  don’t  know  what  it  does  yet?
• Unit tests won't catch all the bugs.
A sad misconception
In fact TDD is a design technique and our objections should be:
• Designing takes too much time.
• How could I design first if I don't know what it does yet?
• Designing won't catch all the bugs.
Traditional software development
•Requirements
•Design

•Implementation
•Testing
•Maintenance
TDD is Agile
“Agile”  means:
• Characterized by quickness, lightness, and ease of movement;
nimble.
• Mentally quick or alert

SCRUM

WORKING SOFTWARE

ADAPTABILITY
extreme programming

DAILY

TRANSPARENCY

UNITY

ITERATION

continuous

CRYSTAL

SIMPLICITY
RELEASE
Why TDD
Why TDD
• Ensures quality
• Keeps code clear, simple and testable
• Provides documentation for different team
members
• Repeatable tests
• Enables rapid change
Why TDD
“When  you  already  have  Tests that documents how your code
works  and  also  verifies  every  logical  units,  programmer’s  bugs  
are significantly reduced resulting more time coding, less time
debugging.”
“You  can  confidently refactor your production code without
worrying about breaking it, if you already have test code written,
it  acts  as  safety  net.”
“Tests  on  TDD  describe  the  behaviour of the code you are going
to write. So, tests provides better picture of specification than
documentation written on a paper because test runs.”
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

•
•
•
•

public void init() {
setLayout();
initMovieList();
initMovieField();
initAddButton();
}
private void setLayout() {
getContentPane().setLayout(new FlowLayout());
}
private void initMovieList() {
movieList = new JList(getMovies();
JScrollPane scroller = new JScrollpane(movieList);
getContentPane().add(scroller);
}
private void initMovieField() {
movieField = new JTextField(16);
getContentPane().add(movieField);
}
private void initAddButton() {
addButton = new JButton(“Add”);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myEditor.add(movie.getText());
movieList.setListData(myEditor.getMovies());
}

});
getContentPane().add(addButton);
}

•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Public void init() {
getContentPane().setLayout(new FlowLayout());
movieList = new JList(myEditor.getMoviews());
JScrollPane scroller = new JScrollPane(movieList);
getContentPane().add(scroller);
movieField = new JTextField(16);
getContentPane().add(movieField);
addButton = new JButton(“Add”);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myEditor.add(movie.getText());
movieList.setListData(myEditor.getMovies());
}
});
getContentPane().add(addButton);
}
A Practical Guide - Refactoring
• Extract Method
When a method gets too long or the
logic is too complex to be easily
understood, part of it can be pulled out
into a method of its own.
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

public class Employee {
//0-engineer, 1-salesman, 2-manager
private String departmentName() {
switch (employeeType ) {
case 0:
return  “Engineering”;
case 1:
return  “Sales”;
case 2:
return  “Management”;
default:
return  “Unknown”;
}
}
}

• abstract public class Employee {
•
Public abstract String
departmentName();
• }
• public class Engineer extends Employee {
•
Public String departmentName() {
•
Return  “Engineering”;
•
}
• }
• public class SalesMan extends Employee {
•
Public String departmentName() {
•
Return  “Sales”;
•
}
• }
• public class Manager extends Employee {
•
Public String departmentName() {
•
Return  “Management”;
•
}
• }
A Practical Guide - Refactoring
• Replace Conditional with
Polymorphism
When we find switch statements,
consider creating subclasses to handle
the different cases and get rid of the
switch.
A Practical Guide - Refactoring
•
•
•
•
•
•
•
•
•
•

public Money calculateTotal(){
Money subtotal = getSubtotal();
Money tax = getTaxableSubtotal().times(0.15);
Money total = subtotal.plus(tax);
Boolean qualifiesForDiscount = getSubtotal().asDouble()>100.0;
Money discount = qualifiesForDiscount
?subtotal.times(0.10)
:new Money(0.0);
return total.minus(discount);
}

• public Money calculateTotal(){
•
return getSubtotal().plus((getTaxableSubtotal().times(0.15)))
•
.minus((getSubtotal().asDouble()>100.0)
•
?(getSubtotal().times(0.10))
•
:0);
• }
A Practical Guide - Refactoring
• Introduce Explaining Variable
When we have a complex expression
that is difficult to understand, we can
extract parts of it and store the
intermediate results in well-named
temporary variables. This breaks the
expression into easy to understand
pieces, as well as making the overall
expression clearer.
A Practical Guide - Refactoring
• public int fib(int i) {
•
int result;
•
if(i == 0){
•
result = 0;
•
}else if (i <=2){
•
result = 1;
•
}else {
•
result = fib( i – 1) + fib(i -2);
•
}
•
return result;
• }

• public int fib( int i ){
•
If (i == 0)return 0;
•
If (i <= 2)return 1;
•
return fib(i – 1) + fib(i – 2);
• }
A Practical Guide - Refactoring
• Replace Nested Conditional with Guard
Clauses
Many people have been taught that a
method should have only a single exit
point. There is no reason for this, certainly
not at the expense of clarity. In a method
that should exit under multiple conditions,
this leads to complex, nested conditional
statements. A better, and much clearer
alternative is to use guard clauses to
return under those conditions.
A Practical Guide - Refactoring
•
•
•
•
•
•
•

Extract class
Extract interface
Replace Type Code with Subclasses
Form Template Method
Replace constructor with Factory method
Replace Inheritance with Delegation
Replace magic number with symbolic constant
A Practical Guide - JUnit
• JUnit is a Java tool that allows you to easily write tests.
• It  uses  Annotations  und  Reflection  (see  one  of  the  next
chapters). During execution JUnit runs methods like:
@Test public void ...()
• JUnit offers  assert-methods to formulate your test outcomes.
• Example:
assertEquals(5, model.getCurrentValue());
Here, the order is important: expected value, actual
value, since an error report says: expected 5 but was ...
A Practical Guide - JUnit
The Assertions
1. assertEquals(expected, actual)
2. assertEquals(expected, actual, delta) for
float  and double obligatory; checks if
|expected  −  actual|  <  δ
3. assertNull, assertNotNull
4. assertTrue, assertFalse
5. assertSame, assertNotSame
A Practical Guide - JUnit
Junit Life Cycle
1. JUnit collects all @Test-Methods in your test class via  Reflection.
2. JUnit executes these methods in isolation from each other, and with
undefined  order.
3. JUnit creates a new instance of the test class for each test run
in  order  to  avoid  side  effects  between  tests.
4. Test run:
4.1 An @Before annotated method is executed, if one
exists.
4.2 An @Test-method is executed.
4.3 An @After annotated method is executed, if one exists.
5. This cycle repeats starting from step 3 until all test methods
have been executed.
A Practical Guide - JUnit
Advanced JUnit features
• Predefined  maximum runtime of a test:
@Test(timeout = 1000l)
• Expected exception:
@Test(expected=NullPointerException.class)
• Flow of execution must not come to certain point:
fail("message") makes the test fail anyhow
A Practical Guide - JUnit
Parameterized Tests
Idea: run one test with several parameter sets.
• 1. Annotate your test class with
@RunWith(Parameterized.class).
• 2. Implement a noarg public static method annotated with
@Parameters,returning a Collection of Arrays.
• 3. Each element of the array must contain the expected value
and all required parameters.
• 4. Implement a constructor setting these values to instance
variables of the test.
• 5. Implement one test method using the parameters.
A Practical Guide - JUnit
@RunWith(Parameterized.class)
public class PrimeNumberValidatorTest {
private Integer primeNumber;
private Boolean expectedValidation;
private PrimeNumberValidator primeNumberValidator;
@Before
public void initialize() {
primeNumberValidator = new PrimeNumberValidator();
}

// Each parameter should be placed as an argument here
// Every time runner triggers, it will pass the arguments from parameters we defined
public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) {
this.primeNumber = primeNumber;
this.expectedValidation = expectedValidation;
}
@Parameterized.Parameters
public static Collection primeNumbers() {
return Arrays.asList(new Object[][] {
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false }
});
}

}

// This test will run 4 times since we have 4 parameters defined
@Test
public void testPrimeNumberValidator() {
assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
}
A Practical Guide - JUnit
Tips writing Tests
•
•
•
•
•
•
•

•
•
•
•
•

Test the simple stuff first
Use assertEquals as much as possible
Use the message argument
Keep test methods simple
Test boundary conditions early
Keep your tests independent of each other
Use fined-grained interfaces liberally (make it easier to create and
maintain mock implementations)
Avoid System.out and System.err in your tests
Avoid testing against databases and network resources
Add a main() to your test cases (doing this lets easily run any test from
command line or other tool)
Start with the assert (and continue backwards)
Always write a toString() method (failure reports will be more
informative, saving time and effort)
Thank  you  for  your  patience….

More Related Content

What's hot

Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentTung Nguyen Thanh
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introMaurice De Beijer [MVP]
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Zohirul Alam Tiemoon
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)nedirtv
 
Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?Bertrand Delacretaz
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test frameworkAbner Chih Yi Huang
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test PresentationSayedur Rahman
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomasintuit_india
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 

What's hot (20)

Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Google test training
Google test trainingGoogle test training
Google test training
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?Karate, the black belt of HTTP API testing?
Karate, the black belt of HTTP API testing?
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 

Similar to Test driven development

Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
Kill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsKill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsRoy van Rijn
 
Kill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van RijnKill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van RijnNLJUG
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testingrsg00usa
 

Similar to Test driven development (20)

Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
Kill the mutants - A better way to test your tests
Kill the mutants - A better way to test your testsKill the mutants - A better way to test your tests
Kill the mutants - A better way to test your tests
 
Kill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van RijnKill the mutants and test your tests - Roy van Rijn
Kill the mutants and test your tests - Roy van Rijn
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testing
 

Recently uploaded

Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...FIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPTiSEO AI
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireExakis Nelite
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jNeo4j
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...marcuskenyatta275
 

Recently uploaded (20)

Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 

Test driven development

  • 1. Test Driven Development “TDD  is  not  testing,  it  is  a  design  technique”. Christoforos Nalmpantis
  • 2. What is TDD TDD is a style of development where: • You maintain an exhaustive suite of Programmer Tests • No code goes into production unless it has associated tests • You write the tests first • The tests determine what code you need to write
  • 3. Red – Green - Refactor 1. Write a test that fails RED REFACTOR 3. Eliminate redundancy GREEN 2. Make the code work
  • 4. A sad misconception Because of the name of TDD most inexperienced developers believe it is testing. This leads to the following objections: • Writing unit tests takes too much time. • How  could  I  write  tests  first  if  I  don’t  know  what  it  does  yet? • Unit tests won't catch all the bugs.
  • 5. A sad misconception In fact TDD is a design technique and our objections should be: • Designing takes too much time. • How could I design first if I don't know what it does yet? • Designing won't catch all the bugs.
  • 7. TDD is Agile “Agile”  means: • Characterized by quickness, lightness, and ease of movement; nimble. • Mentally quick or alert SCRUM WORKING SOFTWARE ADAPTABILITY extreme programming DAILY TRANSPARENCY UNITY ITERATION continuous CRYSTAL SIMPLICITY RELEASE
  • 9. Why TDD • Ensures quality • Keeps code clear, simple and testable • Provides documentation for different team members • Repeatable tests • Enables rapid change
  • 10. Why TDD “When  you  already  have  Tests that documents how your code works  and  also  verifies  every  logical  units,  programmer’s  bugs   are significantly reduced resulting more time coding, less time debugging.” “You  can  confidently refactor your production code without worrying about breaking it, if you already have test code written, it  acts  as  safety  net.” “Tests  on  TDD  describe  the  behaviour of the code you are going to write. So, tests provides better picture of specification than documentation written on a paper because test runs.”
  • 11. A Practical Guide - Refactoring • • • • • • • • • • • • • • • • • • • • • • • • • • • • public void init() { setLayout(); initMovieList(); initMovieField(); initAddButton(); } private void setLayout() { getContentPane().setLayout(new FlowLayout()); } private void initMovieList() { movieList = new JList(getMovies(); JScrollPane scroller = new JScrollpane(movieList); getContentPane().add(scroller); } private void initMovieField() { movieField = new JTextField(16); getContentPane().add(movieField); } private void initAddButton() { addButton = new JButton(“Add”); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myEditor.add(movie.getText()); movieList.setListData(myEditor.getMovies()); } }); getContentPane().add(addButton); } • • • • • • • • • • • • • • • • Public void init() { getContentPane().setLayout(new FlowLayout()); movieList = new JList(myEditor.getMoviews()); JScrollPane scroller = new JScrollPane(movieList); getContentPane().add(scroller); movieField = new JTextField(16); getContentPane().add(movieField); addButton = new JButton(“Add”); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myEditor.add(movie.getText()); movieList.setListData(myEditor.getMovies()); } }); getContentPane().add(addButton); }
  • 12. A Practical Guide - Refactoring • Extract Method When a method gets too long or the logic is too complex to be easily understood, part of it can be pulled out into a method of its own.
  • 13. A Practical Guide - Refactoring • • • • • • • • • • • • • • • public class Employee { //0-engineer, 1-salesman, 2-manager private String departmentName() { switch (employeeType ) { case 0: return  “Engineering”; case 1: return  “Sales”; case 2: return  “Management”; default: return  “Unknown”; } } } • abstract public class Employee { • Public abstract String departmentName(); • } • public class Engineer extends Employee { • Public String departmentName() { • Return  “Engineering”; • } • } • public class SalesMan extends Employee { • Public String departmentName() { • Return  “Sales”; • } • } • public class Manager extends Employee { • Public String departmentName() { • Return  “Management”; • } • }
  • 14. A Practical Guide - Refactoring • Replace Conditional with Polymorphism When we find switch statements, consider creating subclasses to handle the different cases and get rid of the switch.
  • 15. A Practical Guide - Refactoring • • • • • • • • • • public Money calculateTotal(){ Money subtotal = getSubtotal(); Money tax = getTaxableSubtotal().times(0.15); Money total = subtotal.plus(tax); Boolean qualifiesForDiscount = getSubtotal().asDouble()>100.0; Money discount = qualifiesForDiscount ?subtotal.times(0.10) :new Money(0.0); return total.minus(discount); } • public Money calculateTotal(){ • return getSubtotal().plus((getTaxableSubtotal().times(0.15))) • .minus((getSubtotal().asDouble()>100.0) • ?(getSubtotal().times(0.10)) • :0); • }
  • 16. A Practical Guide - Refactoring • Introduce Explaining Variable When we have a complex expression that is difficult to understand, we can extract parts of it and store the intermediate results in well-named temporary variables. This breaks the expression into easy to understand pieces, as well as making the overall expression clearer.
  • 17. A Practical Guide - Refactoring • public int fib(int i) { • int result; • if(i == 0){ • result = 0; • }else if (i <=2){ • result = 1; • }else { • result = fib( i – 1) + fib(i -2); • } • return result; • } • public int fib( int i ){ • If (i == 0)return 0; • If (i <= 2)return 1; • return fib(i – 1) + fib(i – 2); • }
  • 18. A Practical Guide - Refactoring • Replace Nested Conditional with Guard Clauses Many people have been taught that a method should have only a single exit point. There is no reason for this, certainly not at the expense of clarity. In a method that should exit under multiple conditions, this leads to complex, nested conditional statements. A better, and much clearer alternative is to use guard clauses to return under those conditions.
  • 19. A Practical Guide - Refactoring • • • • • • • Extract class Extract interface Replace Type Code with Subclasses Form Template Method Replace constructor with Factory method Replace Inheritance with Delegation Replace magic number with symbolic constant
  • 20. A Practical Guide - JUnit • JUnit is a Java tool that allows you to easily write tests. • It  uses  Annotations  und  Reflection  (see  one  of  the  next chapters). During execution JUnit runs methods like: @Test public void ...() • JUnit offers  assert-methods to formulate your test outcomes. • Example: assertEquals(5, model.getCurrentValue()); Here, the order is important: expected value, actual value, since an error report says: expected 5 but was ...
  • 21. A Practical Guide - JUnit The Assertions 1. assertEquals(expected, actual) 2. assertEquals(expected, actual, delta) for float  and double obligatory; checks if |expected  −  actual|  <  δ 3. assertNull, assertNotNull 4. assertTrue, assertFalse 5. assertSame, assertNotSame
  • 22. A Practical Guide - JUnit Junit Life Cycle 1. JUnit collects all @Test-Methods in your test class via  Reflection. 2. JUnit executes these methods in isolation from each other, and with undefined  order. 3. JUnit creates a new instance of the test class for each test run in  order  to  avoid  side  effects  between  tests. 4. Test run: 4.1 An @Before annotated method is executed, if one exists. 4.2 An @Test-method is executed. 4.3 An @After annotated method is executed, if one exists. 5. This cycle repeats starting from step 3 until all test methods have been executed.
  • 23. A Practical Guide - JUnit Advanced JUnit features • Predefined  maximum runtime of a test: @Test(timeout = 1000l) • Expected exception: @Test(expected=NullPointerException.class) • Flow of execution must not come to certain point: fail("message") makes the test fail anyhow
  • 24. A Practical Guide - JUnit Parameterized Tests Idea: run one test with several parameter sets. • 1. Annotate your test class with @RunWith(Parameterized.class). • 2. Implement a noarg public static method annotated with @Parameters,returning a Collection of Arrays. • 3. Each element of the array must contain the expected value and all required parameters. • 4. Implement a constructor setting these values to instance variables of the test. • 5. Implement one test method using the parameters.
  • 25. A Practical Guide - JUnit @RunWith(Parameterized.class) public class PrimeNumberValidatorTest { private Integer primeNumber; private Boolean expectedValidation; private PrimeNumberValidator primeNumberValidator; @Before public void initialize() { primeNumberValidator = new PrimeNumberValidator(); } // Each parameter should be placed as an argument here // Every time runner triggers, it will pass the arguments from parameters we defined public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) { this.primeNumber = primeNumber; this.expectedValidation = expectedValidation; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false } }); } } // This test will run 4 times since we have 4 parameters defined @Test public void testPrimeNumberValidator() { assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber)); }
  • 26. A Practical Guide - JUnit Tips writing Tests • • • • • • • • • • • • Test the simple stuff first Use assertEquals as much as possible Use the message argument Keep test methods simple Test boundary conditions early Keep your tests independent of each other Use fined-grained interfaces liberally (make it easier to create and maintain mock implementations) Avoid System.out and System.err in your tests Avoid testing against databases and network resources Add a main() to your test cases (doing this lets easily run any test from command line or other tool) Start with the assert (and continue backwards) Always write a toString() method (failure reports will be more informative, saving time and effort)
  • 27. Thank  you  for  your  patience….