SlideShare une entreprise Scribd logo
1  sur  64
Télécharger pour lire hors ligne
145 © VictorRentea.ro
a training by
Don't be Mocked by your Mocks
victorrentea@gmail.com victorrentea.ro @victorrentea
146 © VictorRentea.ro
a training by
Victor Rentea
Blog, Talks, Goodies:
VictorRentea.ro
Independent Trainer & Consultant
Founder of
Bucharest Software Craftsmanship Community
Java Champion
❤️ Simple Design, Refactoring, Unit Testing ❤️
Technical Training
HibernateSpring Functional Prog
400 days
(100+ online)2000 devs8 years
Training for you or your company: VictorRentea.ro
40 companies
Follow me:
35K 4K 3K
Java PerformanceReactive
Design Patterns Refactoring Unit Testing
any
lang
uage
Unit Testing
150 © VictorRentea.ro
a training by
Decouple a Dependency in Tests
Isolated
versus external systems
Fast
DB, APIs
Test Less Code
Test a layer, by faking the layer below:
WHY?!
Cheating?
layers
151 © VictorRentea.ro
a training by
152 © VictorRentea.ro
a training by
153 © VictorRentea.ro
a training by
him.slap();
154 © VictorRentea.ro
a training by
Mock
Verify a method call
verify(repo).save(…);
Stub
Respond to method calls
when(mock.method())
.thenReturn(…);
Dummy
Avoids Null Pointers
Mock w/o behavior
system.setAuthorizer(new NoopAuthorizer());
https://blog.cleancoder.com/uncle-bob/2014/05/14/TheLittleMocker.html
Fake
Alternative
implementationTest Double
155 © VictorRentea.ro
a training by
Fake
Alternative
implementation
Test Implementation
(eg. storing in a hash map)
when(userRepo.findById(1L))
.thenReturn(u);
// prodCall()
userRepo.save(u); //id=1
// prodCall()
Vs
C# Repository pattern + LINQ queries.
Given you trust LINQ, can be tested with just an in-memory list.
TIP: Consider
if copy-pasting
stubbing
when(...)
.thenAnswer(<callback>);
.. or instead of
dynamic stubs
verify(orderRepo).save(...);
list= orderRepo.findAll();
assert list contains new order
156 © VictorRentea.ro
a training by
Mock
Verify a method call
verify(repo).save(…);
Stub
Respond to method calls
when(mock.method())
.thenReturn(…);
Dummy
Avoids Null Pointers
= Mock w/o behavior
system.setAuthorizer(new NoopAuthorizer());
Fake
Alternative
implementationTest Double
you stub or mock a method
157 © VictorRentea.ro
a training by
Mocks aren't Stubs
https://martinfowler.com/articles/mocksArentStubs.html
Stub Queries, Expect Actions
orderRepo.save(Order)userRepo.findById(id):User
Verify what tested code does
based on user's state
when(repo.findById(…)).thenReturn(user);
out = testedCode();
verify(repo).findById(…);
Since Mockito 2.x stubbed methods are automatically verified by default
2
Command-Query Separation Principle
Need Both?
158 © VictorRentea.ro
a training by
No side effects
No INSERTs, POSTs, queues, files, fields,…
𝑒𝑔. 𝑀𝑎𝑡ℎ𝑒𝑚𝑎𝑡𝑖𝑐𝑎𝑙 𝐹𝑢𝑛𝑐𝑡𝑖𝑜𝑛𝑠: 𝑓 𝑥, 𝑦 = 𝑥2
+ 𝑦
(logging doesn't count)
Referential Transparent
Same arguments ➔ same result
No current time, random, GET, SELECT…
Pure Functions
159 © VictorRentea.ro
a training by
160 © VictorRentea.ro
a training by
161 © VictorRentea.ro
a training by
Side-effects
1) On external systems:
2) On in-memory objects
➔ assert their state after
What can a Unit Test check?
OutputInput Params Feature
(method)
Data from
dependencies
Input+Deps → Output
a) Real: SELECT from test to check the INSERT
b) Mocked: verify repo.save() was called
Input → Output
Pass More IN
Philosophic Slide
aka Interaction Testing
Return Change
Pure Function: 𝑓 𝑥 = 𝑥2
The Simplest Tests
a) Real: SELECT
b) Stub: when.thenReturn.
163 © VictorRentea.ro
a training by
Extract Method
mock
verify(orderRepo).save(…);
stub
when(userRepo.findById()).thenReturn(…);
No mocks
Stubs & Mocks
ArgumentCaptor
SimplerTests
Test This:
x 8 tests
164 © VictorRentea.ro
a training by
= Pure Function
public
Cons: parameter count++
Cons: complex return
165 © VictorRentea.ro
a training by
The Circle of Purity
* idea inspired by Venkat Subramaniam
166 © VictorRentea.ro
a training by
infrastructure
domainfunctional core
3
The Universal Architecture
Side-effects &
Dependencies
Code Dependency
aka Onion
aka Hexagonal
aka Ports-and-Adapters
167 © VictorRentea.ro
a training by
Design the Most Complex Parts of Logic
as Pure Functions
My Point?
168 © VictorRentea.ro
a training by
Pure Functions
Easy to Understand Easy to Test
169 © VictorRentea.ro
a training by
How to test this one ?
NPE
Should other tests also execute createOrder() ?
170 © VictorRentea.ro
a training by
NPE
How to test this one ?
Test OverlapHeavy Tests
YES
Complex
Logic+
NO
(Partial Mock)
YES
Few?
(eg. NPE)
Should other tests also execute createOrder() ?
many
171 © VictorRentea.ro
a training by
Partial Mock?!
(eg @Spy in Mockito)
172 © VictorRentea.ro
a training by
Partial Mock
Mocked Methods
createOrder
Tested Methods
placeOrder
Same Object
173 © VictorRentea.ro
a training by
Missed Design Hint
NPE
Tests
How to test this one ?
Test OverlapHeavy Tests
YES NO
(Partial Mock)
Complex
Logic
Should other tests also execute createOrder() ?
OrderFactory
NO
(Extract to New Class)
Separation By Layers of Abstraction
Complex
Logic
@Mock
many
4
186 © VictorRentea.ro
a training by
What's so bad about them after all ?
But I ❤️ Mocks!
I use them everywhere!
Fragile Tests Inconsistent Tests Incorrect Tests
187 © VictorRentea.ro
a training by
The Downfall of Mocks
188 © VictorRentea.ro
a training by
You have to do a difficult change.
First, you make that change easy (this might be difficult).
Then, you do the easy change.
-- Kent Beck
Changing Existing Code
Preparatory Refactoring
The Need for Refactoring
Production Code
189 © VictorRentea.ro
a training by
We write tests to refactor safely
190 © VictorRentea.ro
a training by
Which is
easier to write?
MockEverything
LessMocks
(w/o functional change requests)
Which is stabler?
A
B
C D
Bdirect dependency
(mock) Dfinal real system
(SELECT)
(mock)
Ctest A+B
together
TEST
At which API to verify?Easier to Write Reliable & Stable
Mocks "Freeze" APIs
eg. Repo
Closer to Spec
B1
B2
Are these Unit Tests?
(all are fresh classes)
191 © VictorRentea.ro
a training by
Unit Testing
What’s a Unit?
It's a unit of behavior
= the smallest part of a feature that you can test in isolation
a method ?
a class ?
a full use-case?
- Kent Beck, inventor of TDD, XP, Unit Testing
It's perfectly fine for unit tests to talk to databases and filesystems! – talk
... as long as your tests are isolated ➔ in-memory DB; Docker
192 © VictorRentea.ro
a training by
193 © VictorRentea.ro
a training by
Don't Mock between newly-created classes
vs Stable Interfaces
✓Standard API
(lib, framework, "platform")
✓Multiple implems
✓Old API
Actually, there's an entire TDD style relying
on mocking not-yet-implemented classes
194 © VictorRentea.ro
a training by
Mocks "Freeze" APIs
Only Mock Stable Interfaces
195 © VictorRentea.ro
a training by
A
B
TEST
Kept in Sync
Inconsistencies
when(b.f(7)).thenReturn(1)
assertEquals(1, b.f(7));
Impossible Test Cases
assertEquals(-1, b.f(null));
b.f(x * 2);Production code:
assertEquals(2, b.f(7));
You test them
separately
196 © VictorRentea.ro
a training by
Testing on the Toilet
197 © VictorRentea.ro
a training by
198 © VictorRentea.ro
a training by
199 © VictorRentea.ro
a training by
200 © VictorRentea.ro
a training by
Test requirements, not implementation details!
James Coplien: https://rbcs-us.com/documents/Why-Most-Unit-Testing-is-Waste.pdf
201 © VictorRentea.ro
a training by
Fragile Tests
(when design changes)
Inconsistencies
(when requirements change)
Incorrect Tests
(when testing in isolation)
Extensive Mocking
202 © VictorRentea.ro
a training by
Test more classes together!
(versus mocking every dependency of the tested class)
205 © VictorRentea.ro
a training by
Large Input Data
Many Tests
A
B
C D
final real system
(SELECT)
TEST
eg. Repo
Testing
Framework
(testing DSL)
GET
Blackbox
Test
verify via
another API call
Build Deeper Tests
Reliable & Stable
Closer to Spec
POST
As deep as you can to keep them
maintainable and reliable
206 © VictorRentea.ro
a training by
A
B
C D
final real system
(SELECT)
TEST
eg. Repo
Testing
Framework
(testing DSL)
GET
Blackbox
Test
verify via
another API call
Build Deeper Tests
Reliable & Stable
Closer to Spec
POST
As deep as you can to keep them
understandable, reliable & fast
Large Input Data
Many Tests
207 © VictorRentea.ro
a training by
It may be cheaper to build
a testing framework
On the medium-long term
test it end-to-end
Like Uncle Bob did (2018)
than mocking the little parts
and
208 © VictorRentea.ro
a training by
is impossible for some use-cases
(exponential number of execution paths)
Decompose Complex Flows in Components
tested independently
But to test it end-to-end
Mocks are Inevitable
209 © VictorRentea.ro
a training by
210 © VictorRentea.ro
a training by
Mock Roles, Not Objects without a clear contract
http://jmock.org/oopsla2004.pdf
Challenge: 🥇
Try to extract an interface from the class you want to mock!
Redesign until that interface makes sense
6
212 © VictorRentea.ro
a training by
A) Test More
STOP
and refactor testsA or prodB,C
How many mocks per @Test
Using MORE?
A
B
C
D
E F
(Including @Before and test super-classes)
High Coupling
C) Redesign Responsibilities8
= dependencies count
213 © VictorRentea.ro
a training by
Hidden Dependencies
214 © VictorRentea.ro
a training by
Hidden Dependencies
Static Library Calls
LocalDate.now();
new
new Date();
Encapsulate in mockable
instances passed in as
dependencies
private TimeProvider time;
System.currentTimeMillis();
217 © VictorRentea.ro
a training by
Best if simple and pure
If you need to Mock it
It should not be an Util!
no polymorphism (proxies, strategy...), global state, no lifecycle management, uncontrolled usage
219 © VictorRentea.ro
a training by
Mocks returning Mocks
Mock data objects (Entities, Value Objects, ...)
Too many mocks
Partial Mocks
Mock Statics
Verify stubbed methods
Check how many times() a call happened
Verify no extra call happen or never()
Capture and assert every argument
Populate Test Instances
Mocking Worst Practices
220 © VictorRentea.ro
a training by
Minimalistic Testing
Test Where The Risk is!
221 © VictorRentea.ro
a training by
222 © VictorRentea.ro
a training by
Then, What to mock?
Legacy Code
As an interim stage
Libraries or External Systems
Mock your adapters
Slow or Unreliable Resources
If impossible to run them in-memory / Dockerized
Well Defined Roles
Try to extract a well defined interface
WireMock?
223 © VictorRentea.ro
a training by
Don't Mock Stuff
just because it's a bit harder to test the entire flow
224 © VictorRentea.ro
a training by
DEVELOPERS!!
What are you?
225 © VictorRentea.ro
a training by
Pure Functions
226 © VictorRentea.ro
a training by
226
¡¡ PLEASE !!
Ask me questions!
227 © VictorRentea.ro
a training by
Thank You!
VictorRentea.ro
Blog⭐, Company Training, Masterclasses, Best Talks,...
@VictorRenteavictorrentea@gmail.com
¡¡ PLEASE !!
Ask me questions!
Training Topics:
▪ Clean Code + Refactoring
▪ Design Patterns
▪ Unit Testing + TDD
▪ Advanced FP with Java
▪ Spring
▪ Hibernate/JPA
▪ Reactive Programming
▪ Java Performance
▪ Pragmatic DDD

Contenu connexe

Tendances

Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfVictor Rentea
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteVictor Rentea
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor Rentea
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor Rentea
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxVictor Rentea
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeScott Wlaschin
 
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
 

Tendances (20)

Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Clean Code
Clean CodeClean Code
Clean Code
 
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
Clean code
Clean codeClean code
Clean code
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
 
Clean Code
Clean CodeClean Code
Clean Code
 
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
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 

Similaire à Don't Be Mocked by your Mocks - Best Practices using Mocks

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
 
Simple tools to fight bigger quality battle
Simple tools to fight bigger quality battleSimple tools to fight bigger quality battle
Simple tools to fight bigger quality battleAnand Ramdeo
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Fwdays
 
Continuous delivery from the trenches
Continuous delivery from the trenchesContinuous delivery from the trenches
Continuous delivery from the trenchesMichael Medin
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hintsVictor Rentea
 
Easy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEasy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEric Potter
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.Matt Eland
 
Rise of the Machines - Automate your Development
Rise of the Machines - Automate your DevelopmentRise of the Machines - Automate your Development
Rise of the Machines - Automate your DevelopmentSven Peters
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinSigma Software
 
Windmill Testing certification
Windmill Testing certificationWindmill Testing certification
Windmill Testing certificationVskills
 
Java Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth RoundJava Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth RoundAnnibale Panichella
 
IoT Best Practices: Unit Testing
IoT Best Practices: Unit TestingIoT Best Practices: Unit Testing
IoT Best Practices: Unit Testingfarmckon
 
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Cωνσtantίnoς Giannoulis
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certificationVskills
 
Test-Driven Development Introduction
Test-Driven Development IntroductionTest-Driven Development Introduction
Test-Driven Development IntroductionSamsung Electronics
 
Stop Being Lazy and Test Your Software
Stop Being Lazy and Test Your SoftwareStop Being Lazy and Test Your Software
Stop Being Lazy and Test Your SoftwareLaura Frank Tacho
 
Troubleshooting tips from docker support engineers
Troubleshooting tips from docker support engineersTroubleshooting tips from docker support engineers
Troubleshooting tips from docker support engineersDocker, Inc.
 
How EVERFI Moved from No Automation to Continuous Test Generation in 9 Months
How EVERFI Moved from No Automation to Continuous Test Generation in 9 MonthsHow EVERFI Moved from No Automation to Continuous Test Generation in 9 Months
How EVERFI Moved from No Automation to Continuous Test Generation in 9 MonthsApplitools
 

Similaire à Don't Be Mocked by your Mocks - Best Practices using Mocks (20)

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...
 
Simple tools to fight bigger quality battle
Simple tools to fight bigger quality battleSimple tools to fight bigger quality battle
Simple tools to fight bigger quality battle
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"
 
Continuous delivery from the trenches
Continuous delivery from the trenchesContinuous delivery from the trenches
Continuous delivery from the trenches
 
Test
TestTest
Test
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Easy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEasy Automated UI Testing with Canopy
Easy Automated UI Testing with Canopy
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.
 
Harton-Presentation
Harton-PresentationHarton-Presentation
Harton-Presentation
 
Rise of the Machines - Automate your Development
Rise of the Machines - Automate your DevelopmentRise of the Machines - Automate your Development
Rise of the Machines - Automate your Development
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
Windmill Testing certification
Windmill Testing certificationWindmill Testing certification
Windmill Testing certification
 
Java Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth RoundJava Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth Round
 
IoT Best Practices: Unit Testing
IoT Best Practices: Unit TestingIoT Best Practices: Unit Testing
IoT Best Practices: Unit Testing
 
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
Lessons Learned in Software Development: QA Infrastructure – Maintaining Rob...
 
the grinder testing certification
the grinder testing certificationthe grinder testing certification
the grinder testing certification
 
Test-Driven Development Introduction
Test-Driven Development IntroductionTest-Driven Development Introduction
Test-Driven Development Introduction
 
Stop Being Lazy and Test Your Software
Stop Being Lazy and Test Your SoftwareStop Being Lazy and Test Your Software
Stop Being Lazy and Test Your Software
 
Troubleshooting tips from docker support engineers
Troubleshooting tips from docker support engineersTroubleshooting tips from docker support engineers
Troubleshooting tips from docker support engineers
 
How EVERFI Moved from No Automation to Continuous Test Generation in 9 Months
How EVERFI Moved from No Automation to Continuous Test Generation in 9 MonthsHow EVERFI Moved from No Automation to Continuous Test Generation in 9 Months
How EVERFI Moved from No Automation to Continuous Test Generation in 9 Months
 

Plus de Victor Rentea

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Victor Rentea
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdfVictor Rentea
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfVictor Rentea
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021Victor Rentea
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicVictor Rentea
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzVictor Rentea
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021Victor Rentea
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Victor Rentea
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Victor Rentea
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable ObjectsVictor Rentea
 
Definitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaDefinitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaVictor Rentea
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipVictor Rentea
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Victor Rentea
 

Plus de Victor Rentea (18)

Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdf
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Definitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaDefinitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in Java
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
 

Dernier

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 

Dernier (20)

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

Don't Be Mocked by your Mocks - Best Practices using Mocks

  • 1. 145 © VictorRentea.ro a training by Don't be Mocked by your Mocks victorrentea@gmail.com victorrentea.ro @victorrentea
  • 3. Victor Rentea Blog, Talks, Goodies: VictorRentea.ro Independent Trainer & Consultant Founder of Bucharest Software Craftsmanship Community Java Champion ❤️ Simple Design, Refactoring, Unit Testing ❤️
  • 4. Technical Training HibernateSpring Functional Prog 400 days (100+ online)2000 devs8 years Training for you or your company: VictorRentea.ro 40 companies Follow me: 35K 4K 3K Java PerformanceReactive Design Patterns Refactoring Unit Testing any lang uage
  • 6. 150 © VictorRentea.ro a training by Decouple a Dependency in Tests Isolated versus external systems Fast DB, APIs Test Less Code Test a layer, by faking the layer below: WHY?! Cheating? layers
  • 9. 153 © VictorRentea.ro a training by him.slap();
  • 10. 154 © VictorRentea.ro a training by Mock Verify a method call verify(repo).save(…); Stub Respond to method calls when(mock.method()) .thenReturn(…); Dummy Avoids Null Pointers Mock w/o behavior system.setAuthorizer(new NoopAuthorizer()); https://blog.cleancoder.com/uncle-bob/2014/05/14/TheLittleMocker.html Fake Alternative implementationTest Double
  • 11. 155 © VictorRentea.ro a training by Fake Alternative implementation Test Implementation (eg. storing in a hash map) when(userRepo.findById(1L)) .thenReturn(u); // prodCall() userRepo.save(u); //id=1 // prodCall() Vs C# Repository pattern + LINQ queries. Given you trust LINQ, can be tested with just an in-memory list. TIP: Consider if copy-pasting stubbing when(...) .thenAnswer(<callback>); .. or instead of dynamic stubs verify(orderRepo).save(...); list= orderRepo.findAll(); assert list contains new order
  • 12. 156 © VictorRentea.ro a training by Mock Verify a method call verify(repo).save(…); Stub Respond to method calls when(mock.method()) .thenReturn(…); Dummy Avoids Null Pointers = Mock w/o behavior system.setAuthorizer(new NoopAuthorizer()); Fake Alternative implementationTest Double you stub or mock a method
  • 13. 157 © VictorRentea.ro a training by Mocks aren't Stubs https://martinfowler.com/articles/mocksArentStubs.html Stub Queries, Expect Actions orderRepo.save(Order)userRepo.findById(id):User Verify what tested code does based on user's state when(repo.findById(…)).thenReturn(user); out = testedCode(); verify(repo).findById(…); Since Mockito 2.x stubbed methods are automatically verified by default 2 Command-Query Separation Principle Need Both?
  • 14. 158 © VictorRentea.ro a training by No side effects No INSERTs, POSTs, queues, files, fields,… 𝑒𝑔. 𝑀𝑎𝑡ℎ𝑒𝑚𝑎𝑡𝑖𝑐𝑎𝑙 𝐹𝑢𝑛𝑐𝑡𝑖𝑜𝑛𝑠: 𝑓 𝑥, 𝑦 = 𝑥2 + 𝑦 (logging doesn't count) Referential Transparent Same arguments ➔ same result No current time, random, GET, SELECT… Pure Functions
  • 17. 161 © VictorRentea.ro a training by Side-effects 1) On external systems: 2) On in-memory objects ➔ assert their state after What can a Unit Test check? OutputInput Params Feature (method) Data from dependencies Input+Deps → Output a) Real: SELECT from test to check the INSERT b) Mocked: verify repo.save() was called Input → Output Pass More IN Philosophic Slide aka Interaction Testing Return Change Pure Function: 𝑓 𝑥 = 𝑥2 The Simplest Tests a) Real: SELECT b) Stub: when.thenReturn.
  • 18. 163 © VictorRentea.ro a training by Extract Method mock verify(orderRepo).save(…); stub when(userRepo.findById()).thenReturn(…); No mocks Stubs & Mocks ArgumentCaptor SimplerTests Test This: x 8 tests
  • 19. 164 © VictorRentea.ro a training by = Pure Function public Cons: parameter count++ Cons: complex return
  • 20. 165 © VictorRentea.ro a training by The Circle of Purity * idea inspired by Venkat Subramaniam
  • 21. 166 © VictorRentea.ro a training by infrastructure domainfunctional core 3 The Universal Architecture Side-effects & Dependencies Code Dependency aka Onion aka Hexagonal aka Ports-and-Adapters
  • 22. 167 © VictorRentea.ro a training by Design the Most Complex Parts of Logic as Pure Functions My Point?
  • 23. 168 © VictorRentea.ro a training by Pure Functions Easy to Understand Easy to Test
  • 24. 169 © VictorRentea.ro a training by How to test this one ? NPE Should other tests also execute createOrder() ?
  • 25. 170 © VictorRentea.ro a training by NPE How to test this one ? Test OverlapHeavy Tests YES Complex Logic+ NO (Partial Mock) YES Few? (eg. NPE) Should other tests also execute createOrder() ? many
  • 26. 171 © VictorRentea.ro a training by Partial Mock?! (eg @Spy in Mockito)
  • 27. 172 © VictorRentea.ro a training by Partial Mock Mocked Methods createOrder Tested Methods placeOrder Same Object
  • 28. 173 © VictorRentea.ro a training by Missed Design Hint NPE Tests How to test this one ? Test OverlapHeavy Tests YES NO (Partial Mock) Complex Logic Should other tests also execute createOrder() ? OrderFactory NO (Extract to New Class) Separation By Layers of Abstraction Complex Logic @Mock many 4
  • 29. 186 © VictorRentea.ro a training by What's so bad about them after all ? But I ❤️ Mocks! I use them everywhere! Fragile Tests Inconsistent Tests Incorrect Tests
  • 30. 187 © VictorRentea.ro a training by The Downfall of Mocks
  • 31. 188 © VictorRentea.ro a training by You have to do a difficult change. First, you make that change easy (this might be difficult). Then, you do the easy change. -- Kent Beck Changing Existing Code Preparatory Refactoring The Need for Refactoring Production Code
  • 32. 189 © VictorRentea.ro a training by We write tests to refactor safely
  • 33. 190 © VictorRentea.ro a training by Which is easier to write? MockEverything LessMocks (w/o functional change requests) Which is stabler? A B C D Bdirect dependency (mock) Dfinal real system (SELECT) (mock) Ctest A+B together TEST At which API to verify?Easier to Write Reliable & Stable Mocks "Freeze" APIs eg. Repo Closer to Spec B1 B2 Are these Unit Tests? (all are fresh classes)
  • 34. 191 © VictorRentea.ro a training by Unit Testing What’s a Unit? It's a unit of behavior = the smallest part of a feature that you can test in isolation a method ? a class ? a full use-case? - Kent Beck, inventor of TDD, XP, Unit Testing It's perfectly fine for unit tests to talk to databases and filesystems! – talk ... as long as your tests are isolated ➔ in-memory DB; Docker
  • 36. 193 © VictorRentea.ro a training by Don't Mock between newly-created classes vs Stable Interfaces ✓Standard API (lib, framework, "platform") ✓Multiple implems ✓Old API Actually, there's an entire TDD style relying on mocking not-yet-implemented classes
  • 37. 194 © VictorRentea.ro a training by Mocks "Freeze" APIs Only Mock Stable Interfaces
  • 38. 195 © VictorRentea.ro a training by A B TEST Kept in Sync Inconsistencies when(b.f(7)).thenReturn(1) assertEquals(1, b.f(7)); Impossible Test Cases assertEquals(-1, b.f(null)); b.f(x * 2);Production code: assertEquals(2, b.f(7)); You test them separately
  • 39. 196 © VictorRentea.ro a training by Testing on the Toilet
  • 43. 200 © VictorRentea.ro a training by Test requirements, not implementation details! James Coplien: https://rbcs-us.com/documents/Why-Most-Unit-Testing-is-Waste.pdf
  • 44. 201 © VictorRentea.ro a training by Fragile Tests (when design changes) Inconsistencies (when requirements change) Incorrect Tests (when testing in isolation) Extensive Mocking
  • 45. 202 © VictorRentea.ro a training by Test more classes together! (versus mocking every dependency of the tested class)
  • 46. 205 © VictorRentea.ro a training by Large Input Data Many Tests A B C D final real system (SELECT) TEST eg. Repo Testing Framework (testing DSL) GET Blackbox Test verify via another API call Build Deeper Tests Reliable & Stable Closer to Spec POST As deep as you can to keep them maintainable and reliable
  • 47. 206 © VictorRentea.ro a training by A B C D final real system (SELECT) TEST eg. Repo Testing Framework (testing DSL) GET Blackbox Test verify via another API call Build Deeper Tests Reliable & Stable Closer to Spec POST As deep as you can to keep them understandable, reliable & fast Large Input Data Many Tests
  • 48. 207 © VictorRentea.ro a training by It may be cheaper to build a testing framework On the medium-long term test it end-to-end Like Uncle Bob did (2018) than mocking the little parts and
  • 49. 208 © VictorRentea.ro a training by is impossible for some use-cases (exponential number of execution paths) Decompose Complex Flows in Components tested independently But to test it end-to-end Mocks are Inevitable
  • 51. 210 © VictorRentea.ro a training by Mock Roles, Not Objects without a clear contract http://jmock.org/oopsla2004.pdf Challenge: 🥇 Try to extract an interface from the class you want to mock! Redesign until that interface makes sense 6
  • 52. 212 © VictorRentea.ro a training by A) Test More STOP and refactor testsA or prodB,C How many mocks per @Test Using MORE? A B C D E F (Including @Before and test super-classes) High Coupling C) Redesign Responsibilities8 = dependencies count
  • 53. 213 © VictorRentea.ro a training by Hidden Dependencies
  • 54. 214 © VictorRentea.ro a training by Hidden Dependencies Static Library Calls LocalDate.now(); new new Date(); Encapsulate in mockable instances passed in as dependencies private TimeProvider time; System.currentTimeMillis();
  • 55. 217 © VictorRentea.ro a training by Best if simple and pure If you need to Mock it It should not be an Util! no polymorphism (proxies, strategy...), global state, no lifecycle management, uncontrolled usage
  • 56. 219 © VictorRentea.ro a training by Mocks returning Mocks Mock data objects (Entities, Value Objects, ...) Too many mocks Partial Mocks Mock Statics Verify stubbed methods Check how many times() a call happened Verify no extra call happen or never() Capture and assert every argument Populate Test Instances Mocking Worst Practices
  • 57. 220 © VictorRentea.ro a training by Minimalistic Testing Test Where The Risk is!
  • 59. 222 © VictorRentea.ro a training by Then, What to mock? Legacy Code As an interim stage Libraries or External Systems Mock your adapters Slow or Unreliable Resources If impossible to run them in-memory / Dockerized Well Defined Roles Try to extract a well defined interface WireMock?
  • 60. 223 © VictorRentea.ro a training by Don't Mock Stuff just because it's a bit harder to test the entire flow
  • 61. 224 © VictorRentea.ro a training by DEVELOPERS!! What are you?
  • 62. 225 © VictorRentea.ro a training by Pure Functions
  • 63. 226 © VictorRentea.ro a training by 226 ¡¡ PLEASE !! Ask me questions!
  • 64. 227 © VictorRentea.ro a training by Thank You! VictorRentea.ro Blog⭐, Company Training, Masterclasses, Best Talks,... @VictorRenteavictorrentea@gmail.com ¡¡ PLEASE !! Ask me questions! Training Topics: ▪ Clean Code + Refactoring ▪ Design Patterns ▪ Unit Testing + TDD ▪ Advanced FP with Java ▪ Spring ▪ Hibernate/JPA ▪ Reactive Programming ▪ Java Performance ▪ Pragmatic DDD