SlideShare a Scribd company logo
Scott Leberknight
6/28/2019
(Unit) Testing
Why Test?
Unit Testing
Does your code work?
How do you know?
Tests provide some level of confidence
your code does what you think it does…
…which is not the same as saying
the code is correct
from a business perspective
Tests cannot and will not ever
catch or prevent all possible problems
You might have a passing test suite but
still have logic bugs…
e.g. due to poorly defined or
understood requirements, poor
design, etc.
Unit Testing
“In the 737 Max, only one of the flight
management computers is active at a time -
either the pilot’s computer or the copilot’s
computer.And the active computer takes
inputs only from the sensors on its own side
of the aircraft.”
https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
“When the two computers disagree, the
solution for the humans in the cockpit is 

to look across the control panel to see

what the other instruments are saying and
then sort it out. In the Boeing system, the
flight management computer does not “look 

across” at the other instruments. It 

believes only the instruments on its side.”
https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
“This means that if a particular angle-of-
attack sensor goes haywire - which happens
all the time in a machine that alternates
from one extreme environment to another,
vibrating and shaking all the way - the flight
management computer just believes it.”
https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
Unit Testing
“The primary cause of this discrepancy was that one piece of ground
software supplied by Lockheed Martin produced results in a United
States customary unit, contrary to its Software Interface Specification
(SIS), while a second system, supplied by NASA, expected those
results to be in SI units, in accordance with the SIS. Specifically,
software that calculated the total impulse produced by thruster
firings produced results in pound-force seconds.The trajectory
calculation software then used these results – expected to be in
newton seconds – to update the predicted position of the
spacecraft.”
https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure
The act of testing makes you consider more
than just the “happy path”
Many Flavors…
“Unit” Integration
Performance
Functional (QA)
Security
User interface
Other…?Exploratory
Good testing…
Automated
Repeatable
Continuous
(“ARC” testing)
Good unit testing…
Fast (a few milliseconds?)
Isolated (no “real” dependencies)
Consider success & failure modes
What is a “unit” test?
Not always clearly defined
A single class? A single function?
Can it touch external resources?
(e.g. a database, web service, or file system)
@Test
fun `contribution should be sum of salary & Roth deferrals`() {
assertThat(payroll.totalContribution)
.isEqualTo(payroll.salaryDeferral +
payroll.rothDeferral)
}
A simple unit test
Potential Benefits
Find regressions quickly
Confidence
Better design (*)
(*) probably…
You can go faster in the long run
Potential Pitfalls
False confidence
Tests can have bugs too…
(*) debatable, but not in my personal experience…
You might be slower in short run (*)
What to test?
“Business” logic…
Persistence logic…
User interfaces…
“Anything that can possibly break” ???
What to test?
Test your code…
…not your dependencies
What to test?
More generally you should assume
libraries, frameworks, operating systems,
etc. have been tested and work as
advertised…
(obviously there are caveats to the above)
How to test?
TDD (Test-Driven Development aka “test first”)
TAST (test at same time, commit only tested code)
Test after (avoid…or deal with the consequences)
…on “legacy code” this is your only option
“Legacy Code”
“To me, legacy code is simply
code without tests”
- Michael Feathers,
Working Effectively with Legacy Code
“TDD”
Test-driven development
Usually associated with “test first”
Write failing test, write simplest code
to make it pass, repeat…
“Red-Green-Refactor” cycle
“TDD”
Can you be test-driven without test first?
I think you can…
By letting tests drive the design…
And guide towards “testable” code…
Tests & Design
What does “testable” code mean?
* Loosely coupled, e.g. injecting dependencies
* Separation of concerns
* Single Responsibility Principle (SRP)
Tests & Design
What does “testable” code look like?
* Smaller classes in OO languages
* Smaller methods/functions (7-10 lines max? 20? 30?)
* Injected dependencies, e.g. via constructors or
function parameters
* More “pure” functions
Tests & Design
Why do these things make code testable?
* Facilitates “mocking” dependencies, e.g. a credit
card processing web service, or persistence to a
database
* A function that accepts input, has no side effects,
and produces a consistent output is much easier
to test
Testing Techniques
Prefer smaller, targeted tests (less coupling)
Mock objects (but don’t overdo it)
Perform assertions on return values
Verify behavior of mock objects
(correct methods called, expected arguments)
Testing Techniques
Property-based testing
Test “units” and mock dependencies
Generative testing
Measuring code “covered” by tests
Example test using a mock
@ExtendWith(DropwizardExtensionsSupport.class)
class RelationshipResourceTest {
private static final RelationshipService SERVICE = mock(RelationshipService.class);
private static final ResourceExtension RESOURCES = ResourceExtension.builder()
.addResource(new RelationshipResource(SERVICE))
.build();
@AfterEach
void tearDown() {
reset(SERVICE);
}
@Test
@DisplayName("given a valid event should attempt to save the event")
void testRecordEvent() {
ConnectionEvent event =
newConnectionEvent(A_SERVICE_NAME, Direction.OUTBOUND, "some-identifier");
Response response = RESOURCES.target(“/elucidate/event")
.request()
.post(Entity.json(event));
assertThat(response.getStatus()).isEqualTo(202);
verify(SERVICE).createEvent(eq(event));
}
// more tests...
}
Testing Async Code
No sleeps!
Mock the environment
“If we go by the book…hours could seem like days…”
Wait for conditions
(e.g. until a status value is changed)
Unit vs Integration Tests
* A unit test of a single HTTP endpoint accepts
HTTP requests, but uses mock dependencies, e.g.
objects to persist data, or process payments, or
send asynchronous messages
* An integration test of that single HTTP endpoint
accepts HTTP requests, but uses the actual
dependencies…
Code Coverage
How much is “enough”?
Should automated builds fail if
below a threshold? 70%? 80%?
Can/should you test all exceptional
conditions?
Code Coverage
By definition, decoupled, “testable” code
is easier to achieve higher coverage
The goal should not be a number (80%)
The goal is ensuring correct behavior,
output, etc.
Key Takeaways…
Gain confidence that code is “correct”
Automated, repeatable, continuous (ARC)
Tests cannot catch all problems
Better design through “testable code”
Build & change systems faster
(THE END)
Suggested Reading
Clean Code, Robert “Uncle Bob” Martin
Working Effectively with Legacy Code, Michael Feathers
Pragmatic Programmer, Dave Thomas & Andy Hunt
(20th anniversary edition in beta at
https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition)
Suggested Websites
JUnit, de-factor Java unit testing framework, https://junit.org/junit5/
Mockito, mocking library, https://site.mockito.org
AssertJ, fluent assertion library, https://joel-costigliola.github.io/assertj/
Awaitility, async testing library, https://github.com/awaitility/awaitility
Jacoco, code coverage, https://www.jacoco.org/jacoco/
Boeing 737 MAX
https://commons.wikimedia.org/wiki/File:WS_YYC_737_MAX_1.jpg
https://creativecommons.org/licenses/by-sa/4.0/deed.en
No changes made
Photos & Images
(All other images were purchased from iStock)
66MHz Pentium Chip with FDIV flaw
https://en.wikipedia.org/wiki/Pentium_FDIV_bug#/media/
File:KL_Intel_Pentium_A80501.jpg
Konstantin Lanzet
[CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)]
No changes made
Mars Climate Orbiter
https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#/media/
File:Mars_Climate_Orbiter_2.jpg
Public domain
Photos & Images
(All other images were purchased from iStock)
My Info
sleberknight at
fortitudetec.com
www.fortitudetec.com
@sleberknight
scott.leberknight at
gmail
Ad

More Related Content

What's hot (20)

Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
Yong Shean Chong
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
nedirtv
 
Test automation
Test automationTest automation
Test automation
Xavier Yin
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
harinderpisces
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
Shailendra Chauhan
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
Regression testing
Regression testingRegression testing
Regression testing
Anamta Sayyed
 
automation testing benefits
automation testing benefitsautomation testing benefits
automation testing benefits
nazeer pasha
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
David Berliner
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
Raghu Kiran
 
Automation test framework with cucumber – BDD
Automation test framework with cucumber – BDDAutomation test framework with cucumber – BDD
Automation test framework with cucumber – BDD
123abcda
 
What Is Functional Testing?
What Is Functional Testing?What Is Functional Testing?
What Is Functional Testing?
QA InfoTech
 
Test Automation - Keytorc Approach
Test Automation - Keytorc Approach Test Automation - Keytorc Approach
Test Automation - Keytorc Approach
Keytorc Software Testing Services
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
John Blum
 
Testing Tools with AI
Testing Tools with AITesting Tools with AI
Testing Tools with AI
VodqaBLR
 
Introduction to Robot Framework
Introduction to Robot FrameworkIntroduction to Robot Framework
Introduction to Robot Framework
Somkiat Puisungnoen
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
Yong Shean Chong
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
nedirtv
 
Test automation
Test automationTest automation
Test automation
Xavier Yin
 
automation testing benefits
automation testing benefitsautomation testing benefits
automation testing benefits
nazeer pasha
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
David Berliner
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
Raghu Kiran
 
Automation test framework with cucumber – BDD
Automation test framework with cucumber – BDDAutomation test framework with cucumber – BDD
Automation test framework with cucumber – BDD
123abcda
 
What Is Functional Testing?
What Is Functional Testing?What Is Functional Testing?
What Is Functional Testing?
QA InfoTech
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
John Blum
 
Testing Tools with AI
Testing Tools with AITesting Tools with AI
Testing Tools with AI
VodqaBLR
 

Similar to Unit Testing (20)

Testing 101
Testing 101Testing 101
Testing 101
Noam Barkai
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
Caleb Jenkins
 
AAA Automated Testing
AAA Automated TestingAAA Automated Testing
AAA Automated Testing
Francesco Carucci
 
SELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdfSELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdf
Eric Selje
 
Caleb Crandall - Testing Between the Buckets.pptx
Caleb Crandall - Testing Between the Buckets.pptxCaleb Crandall - Testing Between the Buckets.pptx
Caleb Crandall - Testing Between the Buckets.pptx
QA or the Highway
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
Testing in a glance
Testing in a glanceTesting in a glance
Testing in a glance
Rajesh Kumar
 
test
testtest
test
swankydesert4614
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
Caleb Jenkins
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
test
testtest
test
swankydesert4614
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
Ensuring code quality
Ensuring code qualityEnsuring code quality
Ensuring code quality
MikhailVladimirov
 
Design For Testability
Design For TestabilityDesign For Testability
Design For Testability
Giovanni Asproni
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
Facundo Farias
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
Andreas Czakaj
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
Jon Kruger
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Engineering Software Lab
 
SELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdfSELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdf
Eric Selje
 
Caleb Crandall - Testing Between the Buckets.pptx
Caleb Crandall - Testing Between the Buckets.pptxCaleb Crandall - Testing Between the Buckets.pptx
Caleb Crandall - Testing Between the Buckets.pptx
QA or the Highway
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
Testing in a glance
Testing in a glanceTesting in a glance
Testing in a glance
Rajesh Kumar
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
Andreas Czakaj
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
Jon Kruger
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Engineering Software Lab
 
Ad

More from Scott Leberknight (20)

JShell & ki
JShell & kiJShell & ki
JShell & ki
Scott Leberknight
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
Scott Leberknight
 
JDKs 10 to 14 (and beyond)
JDKs 10 to 14 (and beyond)JDKs 10 to 14 (and beyond)
JDKs 10 to 14 (and beyond)
Scott Leberknight
 
SDKMAN!
SDKMAN!SDKMAN!
SDKMAN!
Scott Leberknight
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
Scott Leberknight
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
Scott Leberknight
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
Scott Leberknight
 
httpie
httpiehttpie
httpie
Scott Leberknight
 
jps & jvmtop
jps & jvmtopjps & jvmtop
jps & jvmtop
Scott Leberknight
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
Scott Leberknight
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Google Guava
Google GuavaGoogle Guava
Google Guava
Scott Leberknight
 
Cloudera Impala
Cloudera ImpalaCloudera Impala
Cloudera Impala
Scott Leberknight
 
iOS
iOSiOS
iOS
Scott Leberknight
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
Scott Leberknight
 
HBase Lightning Talk
HBase Lightning TalkHBase Lightning Talk
HBase Lightning Talk
Scott Leberknight
 
Hadoop
HadoopHadoop
Hadoop
Scott Leberknight
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
Scott Leberknight
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Scott Leberknight
 
Ad

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 

Unit Testing

  • 4. Does your code work? How do you know?
  • 5. Tests provide some level of confidence your code does what you think it does…
  • 6. …which is not the same as saying the code is correct from a business perspective
  • 7. Tests cannot and will not ever catch or prevent all possible problems
  • 8. You might have a passing test suite but still have logic bugs… e.g. due to poorly defined or understood requirements, poor design, etc.
  • 10. “In the 737 Max, only one of the flight management computers is active at a time - either the pilot’s computer or the copilot’s computer.And the active computer takes inputs only from the sensors on its own side of the aircraft.” https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
  • 11. “When the two computers disagree, the solution for the humans in the cockpit is 
 to look across the control panel to see
 what the other instruments are saying and then sort it out. In the Boeing system, the flight management computer does not “look 
 across” at the other instruments. It 
 believes only the instruments on its side.” https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
  • 12. “This means that if a particular angle-of- attack sensor goes haywire - which happens all the time in a machine that alternates from one extreme environment to another, vibrating and shaking all the way - the flight management computer just believes it.” https://spectrum.ieee.org/aerospace/aviation/how-the-boeing-737-max-disaster-looks-to-a-software-developer
  • 14. “The primary cause of this discrepancy was that one piece of ground software supplied by Lockheed Martin produced results in a United States customary unit, contrary to its Software Interface Specification (SIS), while a second system, supplied by NASA, expected those results to be in SI units, in accordance with the SIS. Specifically, software that calculated the total impulse produced by thruster firings produced results in pound-force seconds.The trajectory calculation software then used these results – expected to be in newton seconds – to update the predicted position of the spacecraft.” https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure
  • 15. The act of testing makes you consider more than just the “happy path”
  • 16. Many Flavors… “Unit” Integration Performance Functional (QA) Security User interface Other…?Exploratory
  • 18. Good unit testing… Fast (a few milliseconds?) Isolated (no “real” dependencies) Consider success & failure modes
  • 19. What is a “unit” test? Not always clearly defined A single class? A single function? Can it touch external resources? (e.g. a database, web service, or file system)
  • 20. @Test fun `contribution should be sum of salary & Roth deferrals`() { assertThat(payroll.totalContribution) .isEqualTo(payroll.salaryDeferral + payroll.rothDeferral) } A simple unit test
  • 21. Potential Benefits Find regressions quickly Confidence Better design (*) (*) probably… You can go faster in the long run
  • 22. Potential Pitfalls False confidence Tests can have bugs too… (*) debatable, but not in my personal experience… You might be slower in short run (*)
  • 23. What to test? “Business” logic… Persistence logic… User interfaces… “Anything that can possibly break” ???
  • 24. What to test? Test your code… …not your dependencies
  • 25. What to test? More generally you should assume libraries, frameworks, operating systems, etc. have been tested and work as advertised… (obviously there are caveats to the above)
  • 26. How to test? TDD (Test-Driven Development aka “test first”) TAST (test at same time, commit only tested code) Test after (avoid…or deal with the consequences) …on “legacy code” this is your only option
  • 27. “Legacy Code” “To me, legacy code is simply code without tests” - Michael Feathers, Working Effectively with Legacy Code
  • 28. “TDD” Test-driven development Usually associated with “test first” Write failing test, write simplest code to make it pass, repeat… “Red-Green-Refactor” cycle
  • 29. “TDD” Can you be test-driven without test first? I think you can… By letting tests drive the design… And guide towards “testable” code…
  • 30. Tests & Design What does “testable” code mean? * Loosely coupled, e.g. injecting dependencies * Separation of concerns * Single Responsibility Principle (SRP)
  • 31. Tests & Design What does “testable” code look like? * Smaller classes in OO languages * Smaller methods/functions (7-10 lines max? 20? 30?) * Injected dependencies, e.g. via constructors or function parameters * More “pure” functions
  • 32. Tests & Design Why do these things make code testable? * Facilitates “mocking” dependencies, e.g. a credit card processing web service, or persistence to a database * A function that accepts input, has no side effects, and produces a consistent output is much easier to test
  • 33. Testing Techniques Prefer smaller, targeted tests (less coupling) Mock objects (but don’t overdo it) Perform assertions on return values Verify behavior of mock objects (correct methods called, expected arguments)
  • 34. Testing Techniques Property-based testing Test “units” and mock dependencies Generative testing Measuring code “covered” by tests
  • 36. @ExtendWith(DropwizardExtensionsSupport.class) class RelationshipResourceTest { private static final RelationshipService SERVICE = mock(RelationshipService.class); private static final ResourceExtension RESOURCES = ResourceExtension.builder() .addResource(new RelationshipResource(SERVICE)) .build(); @AfterEach void tearDown() { reset(SERVICE); } @Test @DisplayName("given a valid event should attempt to save the event") void testRecordEvent() { ConnectionEvent event = newConnectionEvent(A_SERVICE_NAME, Direction.OUTBOUND, "some-identifier"); Response response = RESOURCES.target(“/elucidate/event") .request() .post(Entity.json(event)); assertThat(response.getStatus()).isEqualTo(202); verify(SERVICE).createEvent(eq(event)); } // more tests... }
  • 37. Testing Async Code No sleeps! Mock the environment “If we go by the book…hours could seem like days…” Wait for conditions (e.g. until a status value is changed)
  • 38. Unit vs Integration Tests * A unit test of a single HTTP endpoint accepts HTTP requests, but uses mock dependencies, e.g. objects to persist data, or process payments, or send asynchronous messages * An integration test of that single HTTP endpoint accepts HTTP requests, but uses the actual dependencies…
  • 39. Code Coverage How much is “enough”? Should automated builds fail if below a threshold? 70%? 80%? Can/should you test all exceptional conditions?
  • 40. Code Coverage By definition, decoupled, “testable” code is easier to achieve higher coverage The goal should not be a number (80%) The goal is ensuring correct behavior, output, etc.
  • 42. Gain confidence that code is “correct” Automated, repeatable, continuous (ARC) Tests cannot catch all problems Better design through “testable code” Build & change systems faster
  • 44. Suggested Reading Clean Code, Robert “Uncle Bob” Martin Working Effectively with Legacy Code, Michael Feathers Pragmatic Programmer, Dave Thomas & Andy Hunt (20th anniversary edition in beta at https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition)
  • 45. Suggested Websites JUnit, de-factor Java unit testing framework, https://junit.org/junit5/ Mockito, mocking library, https://site.mockito.org AssertJ, fluent assertion library, https://joel-costigliola.github.io/assertj/ Awaitility, async testing library, https://github.com/awaitility/awaitility Jacoco, code coverage, https://www.jacoco.org/jacoco/
  • 46. Boeing 737 MAX https://commons.wikimedia.org/wiki/File:WS_YYC_737_MAX_1.jpg https://creativecommons.org/licenses/by-sa/4.0/deed.en No changes made Photos & Images (All other images were purchased from iStock) 66MHz Pentium Chip with FDIV flaw https://en.wikipedia.org/wiki/Pentium_FDIV_bug#/media/ File:KL_Intel_Pentium_A80501.jpg Konstantin Lanzet [CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)] No changes made