SlideShare uma empresa Scribd logo
1 de 79
Imagine a world
without mocks
@KenScambler
Scala Developer at
Me
14 years
5 years
5 years
when possible
when bored
when forced
http://techblog.realestate.com.au/to-kill-a-mockingtest/
Q: What’s so bad about
mocks & stubs?
A: The problem they solve is
“how to test poorly designed
code”
How did we get here?
UserRepo
UserService
User getUser(UserId)
DB
AuthService
boolean authUser(UserId)
Collaborators galore!
Record selectUser(SQL)
UserRepo
UserService
User getUser(UserId)
DB
AuthService
boolean authUser(UserId)
Record selectUser(SQL)
How to separate UserService?
http://martinfowler.com/articles/mocksArentStubs.html
Stubs provide canned answers
to calls made during the test,
usually not responding at all to
anything outside what's
programmed in for the test.
UserService
User getUser(UserId)
If you ask me
“authUser(1234)”,
I’ll say “true”
Stub
UserRepo
DB
Record selectUser(SQL)
UserService
User getUser(UserId)
Stub
UserRepo
Record selectUser(SQL)
UserService’s
input is now
deterministic!
If you ask me
“authUser(1234)”,
I’ll say “true”
DB
http://martinfowler.com/articles/mocksArentStubs.html
Mocks are objects pre-
programmed with
expectations which form a
specification of the calls
they are expected to
receive.
UserService
User getUser(UserId)
I expect
“selectUser()”
to be called once
Mock
If you ask me
“authUser(1234)”,
I’ll say “true”
UserService
User getUser(UserId)
I expect
“selectUser()”
to be called once
Mock
UserService’s
output is now
deterministic!
If you ask me
“authUser(1234)”,
I’ll say “true”
UserService
User getUser(UserId)
Mock
Deterministic
output
Deterministic
input
= Fairly sane test
So far so good.
But wait!
There’s a cost…
1.
Coupled to brittle
implementation
details.
UserService
User getUser(UserId)
Mock
What if an equivalent
method is called
instead? If you ask me
“authUser(1234)”,
I’ll say “true”
authLocalUser(1234)
Stub
UserService
User getUser(UserId)
Ah shit.
authLocalUser(1234)
UserService
User getUser(UserId)
Honestly, no
one’s asked me
that before.
authLocalUser(1234)
UserService
User getUser(UserId)
I’m just a sock.
authLocalUser(1234)
2.
Somewhat misses the
point of the test
UserService
User getUser(UserId)
authLocalUser(1234)
I expect
“selectUser()”
to be called once
Still no idea.
UserService
User getUser(UserId)
IT DIDN’T GET
CALLED!!! NOTHING
HAPPENED!!!!!
UserService
User getUser(UserId)
IT DIDN’T GET
CALLED!!! NOTHING
HAPPENED!!!!!
Real problem:
The stub configuration was
out of date.
Case study #1
Clumsy input
public interface Config {
// Database stuff
String getDatabaseHost();
int getDatabasePort();
int getMaxThreads();
int getConnectionTimeout();
// Potato settings
String getDefaultPotatoVariety();
int getMaxPotatoes();
double getPotatoShininess();
// Sacrificial settings
int getBloodSacrificeGoatCount();
int getBloodSacrificeChickenCount();
int getBloodSacrificeSheepCount();
}
public class PotatoService {
public PotatoService(Config config) {
this.potatoVariety = config.getPotatoVariety();
this.maxPotatoes = config.getMaxPotatoes();
}
public Salad makePotatoSalad() {...}
}
public class PotatoServiceTest {
Config config = mock(Config.class)
@Before
public void before() {
when(config.getDefaultPotatoVariety())
.thenReturn(“pontiac”);
when(config.getMaxPotatoes())
.thenReturn(33);
}
public testMakeSalad() {
PotatoService service = new PotatoService();
Assert.equalTo(service.makeSalad(), ...);
}
}
public class PotatoServiceTest {
Config config = mock(Config.class)
@Before
public void before() {
when(config.getDefaultPotatoVariety())
.thenReturn(“pontiac”);
when(config.getMaxPotatoes())
.thenReturn(33);
}
public testMakeSalad() {
PotatoService service = new PotatoService();
Assert.equalTo(service.makeSalad(), ...);
}
}
Stub
Looks ok. But what is the
stub trying to tell us?
No-ones ever
going to
need all those
things at once.
public interface Config {
// Database stuff
String getDatabaseHost();
int getDatabasePort();
int getMaxThreads();
int getConnectionTimeout();
// Potato settings
String getDefaultPotatoVariety();
int getMaxPotatoes();
double getPotatoShininess();
// Sacrificial settings
int getBloodSacrificeGoatCount();
int getBloodSacrificeChickenCount();
int getBloodSacrificeSheepCount();
}
That’s better!
public interface DatabaseConfig {
String getDatabaseHost();
int getDatabasePort();
int getMaxThreads();
int getConnectionTimeout();
}
public interface PotatoConfig {
String getDefaultPotatoVariety();
int getMaxPotatoes();
double getPotatoShininess();
}
public interface SacrificialConfig {
int getBloodSacrificeGoatCount();
int getBloodSacrificeChickenCount();
int getBloodSacrificeSheepCount();
}
public class PotatoService {
public PotatoService(PotatoConfig config) {
this.potatoVariety = config.getPotatoVariety();
this.maxPotatoes = config.getMaxPotatoes();
}
public Salad makePotatoSalad() {...}
}
Don’t you just need the two
fields? Does it matter where
they come from?
public class PotatoService {
public PotatoService(String variety, int max) {
this.potatoVariety = variety;
this.maxPotatoes = max;
}
public Salad makePotatoSalad() {...}
}
The application wiring can
be someone else’s business.
public class PotatoServiceTest {
public testMakeSalad() {
PotatoService service =
new PotatoService(“pontiac”, 33);
Assert.equalTo(service.makeSalad(), ...);
}
}
- More modular
- More reusable
- Simpler
- Less code
- Stubs are gone
Case study #2
Unnecessary mutable
state
public interface Wallet {
int removeCoins(int amount);
int getAmount();
}
public interface VendingMachine {
void insertCoins(int amount);
Can collectCan();
int getStoredCash();
}
public interface Customer {
void buyDrink();
}
public class CustomerTest {
Wallet wallet = mock(Wallet.class);
VendingMachine machine = mock(VendingMachine.class);
@Before
public void before() {
when(wallet.removeCoins(3)).thenReturn(3);
when(vendingMachine.collectCan())
.thenReturn(new CokeCan());
}
public testBuyDrink() {
Customer c = new Customer();
c.buyDrink();
verify(wallet).removeCoins(3);
verify(vendingMachine).insertCoins(3);
verify(vendingMachine).collectCan();
}
}
public class CustomerTest {
Wallet wallet = mock(Wallet.class);
VendingMachine machine = mock(VendingMachine.class);
@Before
public void before() {
when(wallet.removeCoins(3)).thenReturn(3);
when(vendingMachine.collectCan())
.thenReturn(new CokeCan());
}
public testBuyDrink() {
Customer c = new Customer();
c.buyDrink();
verify(wallet).removeCoins(3);
verify(vendingMachine).insertCoins(3);
verify(vendingMachine).collectCan();
}
}
Stub
Mock
The class under test is
separated now!
But what are the mocks
telling us?
public interface Wallet {
int removeCoins(int amount);
int getAmount();
}
public interface VendingMachine {
void insertCoins(int amount);
Can collectCan();
int getStoredCash();
}
public interface Customer {
void buyDrink();
}
Surely we care about
the resulting state,
not the in-betweeny
verbs.
If the state is just
immutable
values, we don’t
have to force
isolation
public interface Wallet {
int removeCoins(int amount);
int getAmount();
}
public interface VendingMachine {
void insertCoins(int amount);
Can collectCan();
int getStoredCash();
}
public interface Customer {
void buyDrink();
}
public interface Wallet {
int getAmount();
Wallet removeCoins(int amount);
}
public interface VendingMachine {
Optional<Can> getCanInTray();
int getStoredCash();
List<Can> getCansInMachine();
VendingMachine insertCoins(int amount);
VendingMachine collectCan();
}
public interface Customer {
Wallet getWallet();
List<Can> getCansHeld();
Pair<VendingMachine, Customer>
buyDrink(VendingMachine vm);
}
public interface Wallet {
int getAmount();
Wallet removeCoins(int amount);
}
public interface VendingMachine {
Optional<Can> getCanInTray();
int getStoredCash();
List<Can> getCansInMachine();
VendingMachine insertCoins(int amount);
VendingMachine collectCan();
}
public interface Customer {
Wallet getWallet();
List<Can> getCansHeld();
Pair<VendingMachine, Customer>
buyDrink(VendingMachine vm);
}
Immutable
state
public interface Wallet {
int getAmount();
Wallet removeCoins(int amount);
}
public interface VendingMachine {
Optional<Can> getCanInTray();
int getStoredCash();
List<Can> getCansInMachine();
VendingMachine insertCoins(int amount);
VendingMachine collectCan();
}
public interface Customer {
Wallet getWallet();
List<Can> getCansHeld();
Pair<VendingMachine, Customer>
buyDrink(VendingMachine vm);
}
“Actions” just
return new
copies
public class CustomerTest {
public testBuyDrink() {
Customer c = new Customer(new Wallet(23));
VendingMachine vm = new VendingMachine(10,30);
Pair<VendingMachine, Customer> result = c.buyDrink(vm);
Customer c2 = result.second();
VendingMachine vm2 = result.first();
Assert.equals(20, c2.getWallet().getAmount());
Assert.equals(9, vm2.getCansInMachine().size());
Assert.equals(33, vm2.getStoredCash());
}
}
- Less moving parts
- More reusable
- Simpler
- Easier
- Mocks & Stubs are
gone
“But then it’s an
integration test!”
1. Immutable data
structures are just
values.
2. We have no
business peeking at
a method’s tools;
only its results,
effects
3. Pure functions
are already
deterministic
Case study #3
Essential effects
public interface EmailSender {
void sendEmail(String addr, Email email);
}
public class SpecialOffers {
private final EmailSender sender;
void sendSpecialOffers(Customer c) {
if (!c.isUnsubscribed()) {
String content = "Hi " + c.getName() + "!";
sender.sendEmail(c.getEmailAddr(),
new Email(content))
}
}
}
public class SpecialOffersTest {
EmailSender sender = mock(EmailSender.class)
public testSendEmail() {
SpecialOffers offers = new SpecialOffers(sender);
offers.sendSpecialOffers(
new Customer(false, “Bob”, “foo@foo.com”));
verify(sender).send(“foo@foo.com”,
new Email(“Hi, Bob!”));
}
}
public class SpecialOffersTest {
EmailSender sender = mock(EmailSender.class)
public testSendEmail() {
SpecialOffers offers = new SpecialOffers(sender);
offers.sendSpecialOffers(
new Customer(false, “Bob”, “foo@foo.com”));
verify(sender).send(“foo@foo.com”,
new Email(“Hi, Bob!”));
}
}
Mock
Ok, so it tests we send an
email.
But what is the mock trying
to tell us?
public interface EmailSender {
void sendEmail(String addr, Email email);
}
public class SpecialOffers {
private final EmailSender sender;
void sendSpecialOffers(Customer c) {
if (!c.isUnsubscribed()) {
String content = "Hi " + c.getName() + "!";
sender.sendEmail(c.getEmailAddr(),
new Email(content))
}
}
}
I only care about the intent to
send an email, not the actual
sending. Can the intent be its
own thing?
public interface SendEmailIntent {
String getAddress();
Email getEmail();
}
public interface Interpreter {
void interpret(SendEmailIntent intent);
}
public class SpecialOffers {
Optional<SendEmailIntent> sendSpecialOffers(
Customer c) {
if (!c.isUnsubscribed()) {
String content = "Hi " + c.getName() + "!";
return Optional.of(new SendEmailIntent(
c.getEmailAddr(),
new Email(content)));
} else {
return Optional.empty();
}
}
}
We can have
an
interpreter
elsewhere.
public class SpecialOffersTest {
public testSendEmail() {
SpecialOffers offers = new SpecialOffers();
SendEmailIntent intent = offers.sendSpecialOffers(
new Customer(false, “Bob”,
“foo@foo.com”)).get();
Assert.equals(intent.getAddress(), “foo@foo.com”);
Assert.equals(intent.getEmail().getText(),
“Hi, Bob!”);
}
}
- Separated intent
from execution
- More reusable
- Simpler
- Easier
- Mocks are gone
Mocks kill TDD.
TDD = design
methodology
Test-first
encourages you
to design code
well enough to
test…
…and no further.
Mocks & stubs
set a
looooow bar
This totally
guts TDD’s
value for
design.
Conclusion:
Side effects are
the real killer
All I do is make the
input deterministic. If
the input is already
just immutable values,
then you don’t need
me.
Stub Mock
If you’re just using me
because stuff is hard
to create, you need to
get back and design
harder!
Stub Mock
I make output
deterministic, by
recording method
calls instead of
allowing effects.
Stub Mock
Sometimes, this
means that I test a
pointless web of lies,
that doesn’t touch the
code’s reason for
existence.
Stub Mock
Other times, I am really
testing the intent of the
code, which can be pulled
out as its own structure.
This separates the
concern of choosing the
next thing.
Stub Mock
Stub Mock
If you are using
immutable types and
pure functions, then
you’re home and
hosed.
Forget about
• “collaborators”
• “Tell don’t ask”
• Avoiding static methods
• Avoiding “new”.
Imagine a world without mocks

Mais conteúdo relacionado

Mais procurados

Speech recognition project report
Speech recognition project reportSpeech recognition project report
Speech recognition project report
Sarang Afle
 
Final project report
Final project reportFinal project report
Final project report
ssuryawanshi
 

Mais procurados (20)

Pokemon battle simulator (Java Program written on Blue J Editor)
Pokemon battle simulator (Java Program written on Blue J Editor)Pokemon battle simulator (Java Program written on Blue J Editor)
Pokemon battle simulator (Java Program written on Blue J Editor)
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 
Outside-in Test Driven Development - the London School of TDD
Outside-in Test Driven Development - the London School of TDDOutside-in Test Driven Development - the London School of TDD
Outside-in Test Driven Development - the London School of TDD
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
LINEAR BOUNDED AUTOMATA (LBA).pptx
LINEAR BOUNDED AUTOMATA (LBA).pptxLINEAR BOUNDED AUTOMATA (LBA).pptx
LINEAR BOUNDED AUTOMATA (LBA).pptx
 
Tic tac toe game with graphics presentation
Tic  tac  toe game with graphics presentationTic  tac  toe game with graphics presentation
Tic tac toe game with graphics presentation
 
pandas dataframe notes.pdf
pandas dataframe notes.pdfpandas dataframe notes.pdf
pandas dataframe notes.pdf
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Software testing
Software testing Software testing
Software testing
 
Automation Testing Syllabus - Checklist
Automation Testing Syllabus - ChecklistAutomation Testing Syllabus - Checklist
Automation Testing Syllabus - Checklist
 
DBMS Unit III Material
DBMS Unit III MaterialDBMS Unit III Material
DBMS Unit III Material
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdf
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Speech recognition project report
Speech recognition project reportSpeech recognition project report
Speech recognition project report
 
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
 
Final project report
Final project reportFinal project report
Final project report
 

Semelhante a Imagine a world without mocks

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
calderoncasto9163
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irst
jkumaranc
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 

Semelhante a Imagine a world without mocks (20)

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
JavaTalks: OOD principles
JavaTalks: OOD principlesJavaTalks: OOD principles
JavaTalks: OOD principles
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
An Introduction To CQRS
An Introduction To CQRSAn Introduction To CQRS
An Introduction To CQRS
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irst
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 

Mais de kenbot

Mais de kenbot (12)

Grow your own tech leads
Grow your own tech leadsGrow your own tech leads
Grow your own tech leads
 
Applied category theory: the emerging science of compositionality
Applied category theory: the emerging science of compositionalityApplied category theory: the emerging science of compositionality
Applied category theory: the emerging science of compositionality
 
Responsible DI: Ditch the Frameworks
Responsible DI: Ditch the FrameworksResponsible DI: Ditch the Frameworks
Responsible DI: Ditch the Frameworks
 
FP adoption at REA
FP adoption at REAFP adoption at REA
FP adoption at REA
 
Lenses for the masses - introducing Goggles
Lenses for the masses - introducing GogglesLenses for the masses - introducing Goggles
Lenses for the masses - introducing Goggles
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
 
Data made out of functions
Data made out of functionsData made out of functions
Data made out of functions
 
2 Years of Real World FP at REA
2 Years of Real World FP at REA2 Years of Real World FP at REA
2 Years of Real World FP at REA
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
The disaster of mutable state
The disaster of mutable stateThe disaster of mutable state
The disaster of mutable state
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

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
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
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
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
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
 
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 ...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Imagine a world without mocks

  • 1. Imagine a world without mocks @KenScambler Scala Developer at
  • 2.
  • 3.
  • 4. Me 14 years 5 years 5 years when possible when bored when forced
  • 6. Q: What’s so bad about mocks & stubs? A: The problem they solve is “how to test poorly designed code”
  • 7. How did we get here?
  • 10. http://martinfowler.com/articles/mocksArentStubs.html Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
  • 11. UserService User getUser(UserId) If you ask me “authUser(1234)”, I’ll say “true” Stub UserRepo DB Record selectUser(SQL)
  • 12. UserService User getUser(UserId) Stub UserRepo Record selectUser(SQL) UserService’s input is now deterministic! If you ask me “authUser(1234)”, I’ll say “true” DB
  • 13. http://martinfowler.com/articles/mocksArentStubs.html Mocks are objects pre- programmed with expectations which form a specification of the calls they are expected to receive.
  • 14. UserService User getUser(UserId) I expect “selectUser()” to be called once Mock If you ask me “authUser(1234)”, I’ll say “true”
  • 15. UserService User getUser(UserId) I expect “selectUser()” to be called once Mock UserService’s output is now deterministic! If you ask me “authUser(1234)”, I’ll say “true”
  • 17. So far so good.
  • 20. UserService User getUser(UserId) Mock What if an equivalent method is called instead? If you ask me “authUser(1234)”, I’ll say “true” authLocalUser(1234) Stub
  • 22. UserService User getUser(UserId) Honestly, no one’s asked me that before. authLocalUser(1234)
  • 23. UserService User getUser(UserId) I’m just a sock. authLocalUser(1234)
  • 26. UserService User getUser(UserId) IT DIDN’T GET CALLED!!! NOTHING HAPPENED!!!!!
  • 27. UserService User getUser(UserId) IT DIDN’T GET CALLED!!! NOTHING HAPPENED!!!!! Real problem: The stub configuration was out of date.
  • 29. public interface Config { // Database stuff String getDatabaseHost(); int getDatabasePort(); int getMaxThreads(); int getConnectionTimeout(); // Potato settings String getDefaultPotatoVariety(); int getMaxPotatoes(); double getPotatoShininess(); // Sacrificial settings int getBloodSacrificeGoatCount(); int getBloodSacrificeChickenCount(); int getBloodSacrificeSheepCount(); }
  • 30. public class PotatoService { public PotatoService(Config config) { this.potatoVariety = config.getPotatoVariety(); this.maxPotatoes = config.getMaxPotatoes(); } public Salad makePotatoSalad() {...} }
  • 31. public class PotatoServiceTest { Config config = mock(Config.class) @Before public void before() { when(config.getDefaultPotatoVariety()) .thenReturn(“pontiac”); when(config.getMaxPotatoes()) .thenReturn(33); } public testMakeSalad() { PotatoService service = new PotatoService(); Assert.equalTo(service.makeSalad(), ...); } }
  • 32. public class PotatoServiceTest { Config config = mock(Config.class) @Before public void before() { when(config.getDefaultPotatoVariety()) .thenReturn(“pontiac”); when(config.getMaxPotatoes()) .thenReturn(33); } public testMakeSalad() { PotatoService service = new PotatoService(); Assert.equalTo(service.makeSalad(), ...); } } Stub
  • 33. Looks ok. But what is the stub trying to tell us?
  • 34. No-ones ever going to need all those things at once. public interface Config { // Database stuff String getDatabaseHost(); int getDatabasePort(); int getMaxThreads(); int getConnectionTimeout(); // Potato settings String getDefaultPotatoVariety(); int getMaxPotatoes(); double getPotatoShininess(); // Sacrificial settings int getBloodSacrificeGoatCount(); int getBloodSacrificeChickenCount(); int getBloodSacrificeSheepCount(); }
  • 35. That’s better! public interface DatabaseConfig { String getDatabaseHost(); int getDatabasePort(); int getMaxThreads(); int getConnectionTimeout(); } public interface PotatoConfig { String getDefaultPotatoVariety(); int getMaxPotatoes(); double getPotatoShininess(); } public interface SacrificialConfig { int getBloodSacrificeGoatCount(); int getBloodSacrificeChickenCount(); int getBloodSacrificeSheepCount(); }
  • 36. public class PotatoService { public PotatoService(PotatoConfig config) { this.potatoVariety = config.getPotatoVariety(); this.maxPotatoes = config.getMaxPotatoes(); } public Salad makePotatoSalad() {...} } Don’t you just need the two fields? Does it matter where they come from?
  • 37. public class PotatoService { public PotatoService(String variety, int max) { this.potatoVariety = variety; this.maxPotatoes = max; } public Salad makePotatoSalad() {...} } The application wiring can be someone else’s business.
  • 38. public class PotatoServiceTest { public testMakeSalad() { PotatoService service = new PotatoService(“pontiac”, 33); Assert.equalTo(service.makeSalad(), ...); } }
  • 39. - More modular - More reusable - Simpler - Less code - Stubs are gone
  • 40. Case study #2 Unnecessary mutable state
  • 41.
  • 42. public interface Wallet { int removeCoins(int amount); int getAmount(); } public interface VendingMachine { void insertCoins(int amount); Can collectCan(); int getStoredCash(); } public interface Customer { void buyDrink(); }
  • 43. public class CustomerTest { Wallet wallet = mock(Wallet.class); VendingMachine machine = mock(VendingMachine.class); @Before public void before() { when(wallet.removeCoins(3)).thenReturn(3); when(vendingMachine.collectCan()) .thenReturn(new CokeCan()); } public testBuyDrink() { Customer c = new Customer(); c.buyDrink(); verify(wallet).removeCoins(3); verify(vendingMachine).insertCoins(3); verify(vendingMachine).collectCan(); } }
  • 44. public class CustomerTest { Wallet wallet = mock(Wallet.class); VendingMachine machine = mock(VendingMachine.class); @Before public void before() { when(wallet.removeCoins(3)).thenReturn(3); when(vendingMachine.collectCan()) .thenReturn(new CokeCan()); } public testBuyDrink() { Customer c = new Customer(); c.buyDrink(); verify(wallet).removeCoins(3); verify(vendingMachine).insertCoins(3); verify(vendingMachine).collectCan(); } } Stub Mock
  • 45. The class under test is separated now! But what are the mocks telling us?
  • 46. public interface Wallet { int removeCoins(int amount); int getAmount(); } public interface VendingMachine { void insertCoins(int amount); Can collectCan(); int getStoredCash(); } public interface Customer { void buyDrink(); } Surely we care about the resulting state, not the in-betweeny verbs.
  • 47. If the state is just immutable values, we don’t have to force isolation public interface Wallet { int removeCoins(int amount); int getAmount(); } public interface VendingMachine { void insertCoins(int amount); Can collectCan(); int getStoredCash(); } public interface Customer { void buyDrink(); }
  • 48. public interface Wallet { int getAmount(); Wallet removeCoins(int amount); } public interface VendingMachine { Optional<Can> getCanInTray(); int getStoredCash(); List<Can> getCansInMachine(); VendingMachine insertCoins(int amount); VendingMachine collectCan(); } public interface Customer { Wallet getWallet(); List<Can> getCansHeld(); Pair<VendingMachine, Customer> buyDrink(VendingMachine vm); }
  • 49. public interface Wallet { int getAmount(); Wallet removeCoins(int amount); } public interface VendingMachine { Optional<Can> getCanInTray(); int getStoredCash(); List<Can> getCansInMachine(); VendingMachine insertCoins(int amount); VendingMachine collectCan(); } public interface Customer { Wallet getWallet(); List<Can> getCansHeld(); Pair<VendingMachine, Customer> buyDrink(VendingMachine vm); } Immutable state
  • 50. public interface Wallet { int getAmount(); Wallet removeCoins(int amount); } public interface VendingMachine { Optional<Can> getCanInTray(); int getStoredCash(); List<Can> getCansInMachine(); VendingMachine insertCoins(int amount); VendingMachine collectCan(); } public interface Customer { Wallet getWallet(); List<Can> getCansHeld(); Pair<VendingMachine, Customer> buyDrink(VendingMachine vm); } “Actions” just return new copies
  • 51. public class CustomerTest { public testBuyDrink() { Customer c = new Customer(new Wallet(23)); VendingMachine vm = new VendingMachine(10,30); Pair<VendingMachine, Customer> result = c.buyDrink(vm); Customer c2 = result.second(); VendingMachine vm2 = result.first(); Assert.equals(20, c2.getWallet().getAmount()); Assert.equals(9, vm2.getCansInMachine().size()); Assert.equals(33, vm2.getStoredCash()); } }
  • 52. - Less moving parts - More reusable - Simpler - Easier - Mocks & Stubs are gone
  • 53. “But then it’s an integration test!”
  • 54. 1. Immutable data structures are just values.
  • 55. 2. We have no business peeking at a method’s tools; only its results, effects
  • 56. 3. Pure functions are already deterministic
  • 58. public interface EmailSender { void sendEmail(String addr, Email email); } public class SpecialOffers { private final EmailSender sender; void sendSpecialOffers(Customer c) { if (!c.isUnsubscribed()) { String content = "Hi " + c.getName() + "!"; sender.sendEmail(c.getEmailAddr(), new Email(content)) } } }
  • 59. public class SpecialOffersTest { EmailSender sender = mock(EmailSender.class) public testSendEmail() { SpecialOffers offers = new SpecialOffers(sender); offers.sendSpecialOffers( new Customer(false, “Bob”, “foo@foo.com”)); verify(sender).send(“foo@foo.com”, new Email(“Hi, Bob!”)); } }
  • 60. public class SpecialOffersTest { EmailSender sender = mock(EmailSender.class) public testSendEmail() { SpecialOffers offers = new SpecialOffers(sender); offers.sendSpecialOffers( new Customer(false, “Bob”, “foo@foo.com”)); verify(sender).send(“foo@foo.com”, new Email(“Hi, Bob!”)); } } Mock
  • 61. Ok, so it tests we send an email. But what is the mock trying to tell us?
  • 62. public interface EmailSender { void sendEmail(String addr, Email email); } public class SpecialOffers { private final EmailSender sender; void sendSpecialOffers(Customer c) { if (!c.isUnsubscribed()) { String content = "Hi " + c.getName() + "!"; sender.sendEmail(c.getEmailAddr(), new Email(content)) } } } I only care about the intent to send an email, not the actual sending. Can the intent be its own thing?
  • 63. public interface SendEmailIntent { String getAddress(); Email getEmail(); } public interface Interpreter { void interpret(SendEmailIntent intent); } public class SpecialOffers { Optional<SendEmailIntent> sendSpecialOffers( Customer c) { if (!c.isUnsubscribed()) { String content = "Hi " + c.getName() + "!"; return Optional.of(new SendEmailIntent( c.getEmailAddr(), new Email(content))); } else { return Optional.empty(); } } } We can have an interpreter elsewhere.
  • 64. public class SpecialOffersTest { public testSendEmail() { SpecialOffers offers = new SpecialOffers(); SendEmailIntent intent = offers.sendSpecialOffers( new Customer(false, “Bob”, “foo@foo.com”)).get(); Assert.equals(intent.getAddress(), “foo@foo.com”); Assert.equals(intent.getEmail().getText(), “Hi, Bob!”); } }
  • 65. - Separated intent from execution - More reusable - Simpler - Easier - Mocks are gone
  • 68. Test-first encourages you to design code well enough to test…
  • 70. Mocks & stubs set a looooow bar
  • 73. All I do is make the input deterministic. If the input is already just immutable values, then you don’t need me. Stub Mock
  • 74. If you’re just using me because stuff is hard to create, you need to get back and design harder! Stub Mock
  • 75. I make output deterministic, by recording method calls instead of allowing effects. Stub Mock
  • 76. Sometimes, this means that I test a pointless web of lies, that doesn’t touch the code’s reason for existence. Stub Mock
  • 77. Other times, I am really testing the intent of the code, which can be pulled out as its own structure. This separates the concern of choosing the next thing. Stub Mock
  • 78. Stub Mock If you are using immutable types and pure functions, then you’re home and hosed. Forget about • “collaborators” • “Tell don’t ask” • Avoiding static methods • Avoiding “new”.