SlideShare a Scribd company logo
04 BARCELONA
David Ródenas, PhD
TDD Course
TESTING TECHNIQUES
@drpicox
FIRST
TESTING TECHNIQUES 2
@drpicox
@drpicox
Fast


Isolates


Repeatable


Self-validating


Timely
F.I.R.S.T.
3
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
Many hundreds or thousands per second


Avoid slow logic


Data bases


External services


Intensive computations


...
FAST
4
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
Failure reasons become obvious


Each test runs individually


No assumed initial state


Not require other test run
f
irst


Can run alone


Can run in random order


new , new , new


...
ISOLATES
5
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
Run repeatedly in any order, any time


No side effects


No globals/statics


No time


No random


No databases


No services


No split test logic


...
REPEATABLE
6
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
No manual evaluation required


Only two outcomes


Red/Green


Fail/Pass
SELF-VALIDATING
7
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
Written before the code


If you write test after code:


You do not follow TDD


You are not sure that the test works


You forget test behaviours


Your tests become useless


You feel cheeting


...
TIMELY
8
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
const notebook = new Notebook()


test("add a contact", () => {


notebook.add("John", 1234)


expect(notebook.get("John")).toBe(1234)


})


test("update contact", () => {


notebook.update("John", 3456)


expect(notebook.get("John")).toBe(3456)


})


test("remove a contact", () => {


notebook.remove("John")


expect(notebook.get("John")).toBeNull()


})
EXAMPLE
9
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
test("add a contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


expect(notebook.get("John")).toBe(1234)


})


test("update contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


notebook.update("John", 3456)


expect(notebook.get("John")).toBe(3456)


})


test("remove a contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


notebook.remove("John")


expect(notebook.get("John")).toBeNull()


})
EXAMPLE
10
TESTING TECHNIQUES — FIRST
@drpicox
@drpicox
// Date changes each time


new Date();


// Result changes each call


Random.next();


// We are accessing a static/global


Notebook.add("John", 1234);


// Global + It is not self-validated


if (notebook.get("John") === 1234)


System.out.println("Sucess")
EXAMPLE
11
TESTING TECHNIQUES — FIRST
@drpicox
AAA
TESTING TECHNIQUES 12
@drpicox
@drpicox
Arrange


Prepare the initial states


Call news and required sets before act


Act


Execute the actions required by the test


Assert


Gather results


Expect the result values
AAA STRUCTURE
13
TESTING TECHNIQUES — AAA
@drpicox
@drpicox
Order is always kept


Steps are not mixed


Expect always simple results
AAA STRUCTURE
14
TESTING TECHNIQUES — AAA
@drpicox
@drpicox
test("manage contacts", () => {


const notebook = new Notebook() // Arrange


notebook.add("John", 1234) // Act


expect(notebook.get("John")).toBe(1234) // Assert


notebook.update("John", 3456) // Act


expect(notebook.get("John")).toBe(3456) // Assert


notebook.delete("John") // Act


expect(notebook.get("John")).toBeNull() // Assert


})
EXAMPLE
15
TESTING TECHNIQUES — AAA
@drpicox
@drpicox
test("add contact", () => {


// Arrange


const notebook = new Notebook()


// Act


notebook.add("John", 1234)


// Assert


expect(notebook.get("John")).toBe(1234)


})


test("update contact", () => {


// Arrange


const notebook = new Notebook()


notebook.add("John", 1234)


// Act


notebook.update("John", 3456)


// Assert


expect(notebook.get("John")).toBe(3456)


})


...
EXAMPLE
16
TESTING TECHNIQUES — AAA
@drpicox
@drpicox
Dispose/clean resources as fourth A
ANNIHILATE
17
TESTING TECHNIQUES — AAA
AAAA
@drpicox
CODE COVERAGE
TESTING TECHNIQUES 18
@drpicox
@drpicox
CODE COVERAGE
19
TESTING TECHNIQUES — CODE COVERAGE
Code Tested
Code Existing
%
@drpicox
@drpicox
test("add contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


expect(notebook.get("John")).toBe(1234)


})


class Notebook {


add(name, phone) {


if (map.contains(name))


throw new Error(`Cannot add twice ${name}`)


map.put(name, phone)


}


}
EXAMPLE
20
TESTING TECHNIQUES — CODE COVERAGE
Code Coverage: 66%
Uncovered line
@drpicox
@drpicox
test("add contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


expect(notebook.get("John")).toBe(1234)


})


test('cannot add a duplicated contact', () => {


const notebook = new Notebook()


notebook.add("John", 1234)


expect(() => notebook.add('John', 1111)).toThrow()


})


class Notebook {


add(name, phone) {


if (map.contains(name))


throw new Error(`Cannot add twice ${name}`)


map.put(name, phone)


}


}
FIX: ADD TEST
21
TESTING TECHNIQUES — CODE COVERAGE
Code Coverage: 100%
@drpicox
@drpicox
test("add contact", () => {


const notebook = new Notebook()


notebook.add("John", 1234)


expect(notebook.get("John")).toBe(1234)


})


class Notebook {


add(name, phone) {


map.put(name, phone)


}


}


FIX: REMOVE CODE
22
TESTING TECHNIQUES — CODE COVERAGE
Code Coverage: 100%
@drpicox
@drpicox
WHICH FIX IS BETTER?
23
TESTING TECHNIQUES — CODE COVERAGE
IT DEPENDS!
Add a Test Case










Remove uncovered code?
Test Fast replaces (Java) Fail Fast


Does the case make sense?


Is there a business case related?


Can it happen?


It worth the code to maintain?




First to check


Do not modify business cases


Do not add replicated checks
@drpicox
@drpicox
1 test base


1 test per condition


&&, ||, if, while, for, ...


1 test per switch cases + 1 for default


Default is always present, even if it is not written
NUMBER OF TESTS
24
TESTING TECHNIQUES — CODE COVERAGE
@drpicox
@drpicox
Main


Dates


Randoms


Network


...
CANNOT COVER
25
TESTING TECHNIQUES — CODE COVERAGE
@drpicox
@drpicox
LIMITS
26
TESTING TECHNIQUES — CODE COVERAGE
“Every well designed system has at least
one dirty component, usually associated
with main. Nothing outside this component
depends on anything inside it. All
dependencies point outward. This is where
you put switches, factories, and IOC.”
https://twitter.com/unclebobmartin/status/1122138039390806016
@drpicox
@drpicox
100% Code Coverage DO NOT ensure correctness


With TDD Code Coverage should be 100%


It is a hint


it reveals what went wrong


what we missed


which cases we implemented but not planned


shows which code remove
QUALITY
27
TESTING TECHNIQUES — CODE COVERAGE
@drpicox
TESTING DOUBLES
TESTING TECHNIQUES 28
@drpicox
@drpicox
Replaces data/object with one created by the test


5 types


Dummy


Stub


Spy


Mock


Fake
TEST DOUBLES
29
TESTING TECHNIQUES — TESTING DOUBLES
@drpicox
@drpicox
Null, 0 or a plain value that can replace an argument
DUMMY
30
TESTING TECHNIQUES — TESTING DOUBLES
test("count created accounts", () => {


const bank = new Bank()


bank.createAccount("John", null)


expect(bank.count()).toBe(1)


})


class Bank {


createAccount(name, fiscalData) {


accounts.put(name, fiscalData)


}


}
@drpicox
@drpicox
A value need for the test that the code uses
STUB
31
TESTING TECHNIQUES — TESTING DOUBLES
test("gives heads", () => {


const random = {


next() {


return 0


},


}


const result = flipCoin(random)


expect(result).toBe("head")


})


function flipCoin(random) {


if (random.next() < 0.5) return "head"


return "tails"


}
@drpicox
@drpicox
Method that remembers its calls
SPY
32
TESTING TECHNIQUES — TESTING DOUBLES
test("hello world", () => {


const log = []


const outputSpy = message => {


log.push(message)


}


sayHello(outputSpy)


expect(log).toEqual(["hello world"])


})


function sayHello(output) {


output("hello world")


}
@drpicox
@drpicox
A spy that validates correctness and knows the object
MOCK
33
TESTING TECHNIQUES — TESTING DOUBLES
class DiskMock {


log = [];


move(cylinder) {


this.log.push('move', cylinder);


}


write(data) {


this.log.push('write', data)


}


isFormatted() {


return this.log.equals('move', 0, 'write', 0)


}


}


test('formats a disk', () => {


const disk = new DiskMock();


format(disk);


expect(disk.isFormatted()).toBeTrue();


})
@drpicox
@drpicox
An functional object that replaces an original one
FAKE
34
TESTING TECHNIQUES — TESTING DOUBLES
test("deposit cash", () => {


const db = new InMemoryDB()


const bank = new Bank(db)


bank.createAccount("John")


bank.deposit("John", 100)


expect(bank.get("John")).toBe(100)


})
@drpicox
@drpicox
Test Doubles may Reduce Coverage


Although, some cases are necessary


Test Doubles Reduce Con
f
idence
CONFIDENCE
35
TESTING TECHNIQUES — TESTING DOUBLES
@drpicox
E.O.TESTING TECHNIQUES

More Related Content

What's hot (20)

KEY
Inside PyMongo - MongoNYC
Mike Dirolf
 
PDF
Introduction to web programming for java and c# programmers by @drpicox
David Rodenas
 
PDF
Testing: ¿what, how, why?
David Rodenas
 
PDF
Developer Test - Things to Know
vilniusjug
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PPTX
Unit testing patterns for concurrent code
Dror Helper
 
PPTX
We Make Debugging Sucks Less
Alon Fliess
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PPTX
Navigating the xDD Alphabet Soup
Dror Helper
 
PDF
GMock framework
corehard_by
 
PDF
Agile Android
Godfrey Nolan
 
PDF
10 Typical Enterprise Java Problems
Eberhard Wolff
 
PDF
10 Typical Problems in Enterprise Java Applications
Eberhard Wolff
 
DOCX
My java file
Anamika Chauhan
 
PPTX
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
PDF
OCP Java SE 8 Exam - Sample Questions - Exceptions and Assertions
Ganesh Samarthyam
 
PDF
Rechecking SharpDevelop: Any New Bugs?
PVS-Studio
 
KEY
Basic Unit Testing with Mockito
Alexander De Leon
 
PDF
Testing logging in asp dot net core
Rajesh Shirsagar
 
PDF
Test-Tutorial
tutorialsruby
 
Inside PyMongo - MongoNYC
Mike Dirolf
 
Introduction to web programming for java and c# programmers by @drpicox
David Rodenas
 
Testing: ¿what, how, why?
David Rodenas
 
Developer Test - Things to Know
vilniusjug
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Unit testing patterns for concurrent code
Dror Helper
 
We Make Debugging Sucks Less
Alon Fliess
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Navigating the xDD Alphabet Soup
Dror Helper
 
GMock framework
corehard_by
 
Agile Android
Godfrey Nolan
 
10 Typical Enterprise Java Problems
Eberhard Wolff
 
10 Typical Problems in Enterprise Java Applications
Eberhard Wolff
 
My java file
Anamika Chauhan
 
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
OCP Java SE 8 Exam - Sample Questions - Exceptions and Assertions
Ganesh Samarthyam
 
Rechecking SharpDevelop: Any New Bugs?
PVS-Studio
 
Basic Unit Testing with Mockito
Alexander De Leon
 
Testing logging in asp dot net core
Rajesh Shirsagar
 
Test-Tutorial
tutorialsruby
 

Similar to TDD CrashCourse Part5: Testing Techniques (20)

PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
PDF
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
Victor Rentea
 
PPTX
Introduction to Software Testing
Sergio Arroyo
 
PDF
#codemotion2016: Everything you should know about testing to go with @pedro_g...
Sergio Arroyo
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
Test-driven Development (TDD)
Bran van der Meer
 
PDF
Design for Testability
Stefano Dalla Palma
 
PDF
Unit testing - 9 design hints
Victor Rentea
 
PPTX
The tests are trying to tell you [email protected]
Victor Rentea
 
PDF
Intro to JavaScript Testing
Ran Mizrahi
 
PDF
Some testing - Everything you should know about testing to go with @pedro_g_s...
Sergio Arroyo
 
PPTX
TDD Training
Manuela Grindei
 
PDF
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
Ortus Solutions, Corp
 
PDF
Android Test Driven Development & Android Unit Testing
mahmoud ramadan
 
PDF
UI Testing
Josh Black
 
PDF
Testing with Express, Mocha & Chai
Joerg Henning
 
PDF
Don't let your tests slow you down
Daniel Irvine
 
ODP
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
PDF
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
PDF
Crack FREE Gta 5Download Latest Version 2025
waqarcracker5
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
The Joy of Testing - Deep Dive @ Devoxx Belgium 2024
Victor Rentea
 
Introduction to Software Testing
Sergio Arroyo
 
#codemotion2016: Everything you should know about testing to go with @pedro_g...
Sergio Arroyo
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Test-driven Development (TDD)
Bran van der Meer
 
Design for Testability
Stefano Dalla Palma
 
Unit testing - 9 design hints
Victor Rentea
 
The tests are trying to tell you [email protected]
Victor Rentea
 
Intro to JavaScript Testing
Ran Mizrahi
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Sergio Arroyo
 
TDD Training
Manuela Grindei
 
10 Techniques to writing easy yet stupidly thorough unit tests.pdf
Ortus Solutions, Corp
 
Android Test Driven Development & Android Unit Testing
mahmoud ramadan
 
UI Testing
Josh Black
 
Testing with Express, Mocha & Chai
Joerg Henning
 
Don't let your tests slow you down
Daniel Irvine
 
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
Crack FREE Gta 5Download Latest Version 2025
waqarcracker5
 
Ad

More from David Rodenas (16)

PDF
TDD CrashCourse Part2: TDD
David Rodenas
 
PDF
Be professional: We Rule the World
David Rodenas
 
PDF
ES3-2020-P3 TDD Calculator
David Rodenas
 
PDF
ES3-2020-P2 Bowling Game Kata
David Rodenas
 
PDF
ES3-2020-05 Testing
David Rodenas
 
PDF
Vespres
David Rodenas
 
PDF
Faster web pages
David Rodenas
 
PDF
Redux for ReactJS Programmers
David Rodenas
 
PDF
Basic Tutorial of React for Programmers
David Rodenas
 
PPTX
From high school to university and work
David Rodenas
 
PDF
Modules in angular 2.0 beta.1
David Rodenas
 
PDF
Freelance i Enginyeria
David Rodenas
 
PDF
Angular 1.X Community and API Decissions
David Rodenas
 
PDF
JS and patterns
David Rodenas
 
PDF
MVS: An angular MVC
David Rodenas
 
PDF
Mvc - Model: the great forgotten
David Rodenas
 
TDD CrashCourse Part2: TDD
David Rodenas
 
Be professional: We Rule the World
David Rodenas
 
ES3-2020-P3 TDD Calculator
David Rodenas
 
ES3-2020-P2 Bowling Game Kata
David Rodenas
 
ES3-2020-05 Testing
David Rodenas
 
Vespres
David Rodenas
 
Faster web pages
David Rodenas
 
Redux for ReactJS Programmers
David Rodenas
 
Basic Tutorial of React for Programmers
David Rodenas
 
From high school to university and work
David Rodenas
 
Modules in angular 2.0 beta.1
David Rodenas
 
Freelance i Enginyeria
David Rodenas
 
Angular 1.X Community and API Decissions
David Rodenas
 
JS and patterns
David Rodenas
 
MVS: An angular MVC
David Rodenas
 
Mvc - Model: the great forgotten
David Rodenas
 
Ad

Recently uploaded (20)

PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 

TDD CrashCourse Part5: Testing Techniques

  • 1. 04 BARCELONA David Ródenas, PhD TDD Course TESTING TECHNIQUES
  • 4. @drpicox @drpicox Many hundreds or thousands per second Avoid slow logic Data bases External services Intensive computations ... FAST 4 TESTING TECHNIQUES — FIRST
  • 5. @drpicox @drpicox Failure reasons become obvious Each test runs individually No assumed initial state Not require other test run f irst Can run alone Can run in random order new , new , new ... ISOLATES 5 TESTING TECHNIQUES — FIRST
  • 6. @drpicox @drpicox Run repeatedly in any order, any time No side effects No globals/statics No time No random No databases No services No split test logic ... REPEATABLE 6 TESTING TECHNIQUES — FIRST
  • 7. @drpicox @drpicox No manual evaluation required Only two outcomes Red/Green Fail/Pass SELF-VALIDATING 7 TESTING TECHNIQUES — FIRST
  • 8. @drpicox @drpicox Written before the code If you write test after code: You do not follow TDD You are not sure that the test works You forget test behaviours Your tests become useless You feel cheeting ... TIMELY 8 TESTING TECHNIQUES — FIRST
  • 9. @drpicox @drpicox const notebook = new Notebook() test("add a contact", () => { notebook.add("John", 1234) expect(notebook.get("John")).toBe(1234) }) test("update contact", () => { notebook.update("John", 3456) expect(notebook.get("John")).toBe(3456) }) test("remove a contact", () => { notebook.remove("John") expect(notebook.get("John")).toBeNull() }) EXAMPLE 9 TESTING TECHNIQUES — FIRST
  • 10. @drpicox @drpicox test("add a contact", () => { const notebook = new Notebook() notebook.add("John", 1234) expect(notebook.get("John")).toBe(1234) }) test("update contact", () => { const notebook = new Notebook() notebook.add("John", 1234) notebook.update("John", 3456) expect(notebook.get("John")).toBe(3456) }) test("remove a contact", () => { const notebook = new Notebook() notebook.add("John", 1234) notebook.remove("John") expect(notebook.get("John")).toBeNull() }) EXAMPLE 10 TESTING TECHNIQUES — FIRST
  • 11. @drpicox @drpicox // Date changes each time new Date(); // Result changes each call Random.next(); // We are accessing a static/global Notebook.add("John", 1234); // Global + It is not self-validated if (notebook.get("John") === 1234) System.out.println("Sucess") EXAMPLE 11 TESTING TECHNIQUES — FIRST
  • 13. @drpicox @drpicox Arrange Prepare the initial states Call news and required sets before act Act Execute the actions required by the test Assert Gather results Expect the result values AAA STRUCTURE 13 TESTING TECHNIQUES — AAA
  • 14. @drpicox @drpicox Order is always kept Steps are not mixed Expect always simple results AAA STRUCTURE 14 TESTING TECHNIQUES — AAA
  • 15. @drpicox @drpicox test("manage contacts", () => { const notebook = new Notebook() // Arrange notebook.add("John", 1234) // Act expect(notebook.get("John")).toBe(1234) // Assert notebook.update("John", 3456) // Act expect(notebook.get("John")).toBe(3456) // Assert notebook.delete("John") // Act expect(notebook.get("John")).toBeNull() // Assert }) EXAMPLE 15 TESTING TECHNIQUES — AAA
  • 16. @drpicox @drpicox test("add contact", () => { // Arrange const notebook = new Notebook() // Act notebook.add("John", 1234) // Assert expect(notebook.get("John")).toBe(1234) }) test("update contact", () => { // Arrange const notebook = new Notebook() notebook.add("John", 1234) // Act notebook.update("John", 3456) // Assert expect(notebook.get("John")).toBe(3456) }) ... EXAMPLE 16 TESTING TECHNIQUES — AAA
  • 17. @drpicox @drpicox Dispose/clean resources as fourth A ANNIHILATE 17 TESTING TECHNIQUES — AAA AAAA
  • 19. @drpicox @drpicox CODE COVERAGE 19 TESTING TECHNIQUES — CODE COVERAGE Code Tested Code Existing %
  • 20. @drpicox @drpicox test("add contact", () => { const notebook = new Notebook() notebook.add("John", 1234) 
 expect(notebook.get("John")).toBe(1234) }) class Notebook { add(name, phone) { if (map.contains(name)) throw new Error(`Cannot add twice ${name}`) map.put(name, phone) } } EXAMPLE 20 TESTING TECHNIQUES — CODE COVERAGE Code Coverage: 66% Uncovered line
  • 21. @drpicox @drpicox test("add contact", () => { const notebook = new Notebook() notebook.add("John", 1234) expect(notebook.get("John")).toBe(1234) }) test('cannot add a duplicated contact', () => { const notebook = new Notebook() notebook.add("John", 1234) expect(() => notebook.add('John', 1111)).toThrow() }) class Notebook { add(name, phone) { if (map.contains(name)) throw new Error(`Cannot add twice ${name}`) map.put(name, phone) } } FIX: ADD TEST 21 TESTING TECHNIQUES — CODE COVERAGE Code Coverage: 100%
  • 22. @drpicox @drpicox test("add contact", () => { const notebook = new Notebook() notebook.add("John", 1234) expect(notebook.get("John")).toBe(1234) }) class Notebook { add(name, phone) { map.put(name, phone) } } FIX: REMOVE CODE 22 TESTING TECHNIQUES — CODE COVERAGE Code Coverage: 100%
  • 23. @drpicox @drpicox WHICH FIX IS BETTER? 23 TESTING TECHNIQUES — CODE COVERAGE IT DEPENDS! Add a Test Case Remove uncovered code? Test Fast replaces (Java) Fail Fast Does the case make sense? Is there a business case related? Can it happen? It worth the code to maintain? First to check Do not modify business cases Do not add replicated checks
  • 24. @drpicox @drpicox 1 test base 1 test per condition &&, ||, if, while, for, ... 1 test per switch cases + 1 for default Default is always present, even if it is not written NUMBER OF TESTS 24 TESTING TECHNIQUES — CODE COVERAGE
  • 26. @drpicox @drpicox LIMITS 26 TESTING TECHNIQUES — CODE COVERAGE “Every well designed system has at least one dirty component, usually associated with main. Nothing outside this component depends on anything inside it. All dependencies point outward. This is where you put switches, factories, and IOC.” https://twitter.com/unclebobmartin/status/1122138039390806016
  • 27. @drpicox @drpicox 100% Code Coverage DO NOT ensure correctness With TDD Code Coverage should be 100% It is a hint it reveals what went wrong what we missed which cases we implemented but not planned shows which code remove QUALITY 27 TESTING TECHNIQUES — CODE COVERAGE
  • 29. @drpicox @drpicox Replaces data/object with one created by the test 5 types Dummy Stub Spy Mock Fake TEST DOUBLES 29 TESTING TECHNIQUES — TESTING DOUBLES
  • 30. @drpicox @drpicox Null, 0 or a plain value that can replace an argument DUMMY 30 TESTING TECHNIQUES — TESTING DOUBLES test("count created accounts", () => { const bank = new Bank() bank.createAccount("John", null) expect(bank.count()).toBe(1) }) class Bank { createAccount(name, fiscalData) { accounts.put(name, fiscalData) } }
  • 31. @drpicox @drpicox A value need for the test that the code uses STUB 31 TESTING TECHNIQUES — TESTING DOUBLES test("gives heads", () => { const random = { next() { return 0 }, } const result = flipCoin(random) expect(result).toBe("head") }) function flipCoin(random) { if (random.next() < 0.5) return "head" return "tails" }
  • 32. @drpicox @drpicox Method that remembers its calls SPY 32 TESTING TECHNIQUES — TESTING DOUBLES test("hello world", () => { const log = [] const outputSpy = message => { log.push(message) } sayHello(outputSpy) expect(log).toEqual(["hello world"]) }) function sayHello(output) { output("hello world") }
  • 33. @drpicox @drpicox A spy that validates correctness and knows the object MOCK 33 TESTING TECHNIQUES — TESTING DOUBLES class DiskMock { log = []; move(cylinder) { this.log.push('move', cylinder); } write(data) { this.log.push('write', data) } isFormatted() { return this.log.equals('move', 0, 'write', 0) } } test('formats a disk', () => { const disk = new DiskMock(); format(disk); expect(disk.isFormatted()).toBeTrue(); })
  • 34. @drpicox @drpicox An functional object that replaces an original one FAKE 34 TESTING TECHNIQUES — TESTING DOUBLES test("deposit cash", () => { const db = new InMemoryDB() const bank = new Bank(db) bank.createAccount("John") bank.deposit("John", 100) expect(bank.get("John")).toBe(100) })
  • 35. @drpicox @drpicox Test Doubles may Reduce Coverage Although, some cases are necessary Test Doubles Reduce Con f idence CONFIDENCE 35 TESTING TECHNIQUES — TESTING DOUBLES