SlideShare a Scribd company logo
1 of 64
Download to read offline
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

More Related Content

What's hot

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 tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkVictor Rentea
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixVictor Rentea
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next ChapterVictor 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
 
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
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Py.test
Py.testPy.test
Py.testsoasme
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 

What's hot (20)

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 tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
 
Clean Code
Clean CodeClean Code
Clean Code
 
The Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring FrameworkThe Proxy Fairy, and The Magic of Spring Framework
The Proxy Fairy, and The Magic of Spring Framework
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
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
 
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
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Py.test
Py.testPy.test
Py.test
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Mutation testing
Mutation testingMutation testing
Mutation testing
 

Similar to 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
 

Similar to 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
 

More from 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
 
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
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java ApplicationVictor Rentea
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor 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
 
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
 

More from Victor Rentea (20)

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
 
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
 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
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...
 
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
 

Recently uploaded

Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 

Recently uploaded (20)

Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 

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