SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYAnaya Medias Swiss
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An IntroductionSam Brannen
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerKoichi Sakata
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Roman Elizarov
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory OptimizationWei Lin
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022Alexander Ioffe
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정Javajigi Jaesung
 
Test unitaire
Test unitaireTest unitaire
Test unitaireIsenDev
 

What's hot (20)

Pitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONYPitfalls of Object Oriented Programming by SONY
Pitfalls of Object Oriented Programming by SONY
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT Compiler
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Zio in real world
Zio in real worldZio in real world
Zio in real world
 
Practical Object Oriented Models In Sql
Practical Object Oriented Models In SqlPractical Object Oriented Models In Sql
Practical Object Oriented Models In Sql
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정
 
Rest assured
Rest assuredRest assured
Rest assured
 
Test unitaire
Test unitaireTest unitaire
Test unitaire
 

Similar to Imagine a world without mocks

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
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 TestsTomek Kaczanowski
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
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...DroidConTLV
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
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 2016Danny Preussler
 
An Introduction To CQRS
An Introduction To CQRSAn Introduction To CQRS
An Introduction To CQRSNeil Robbins
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant 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___________________________________.pdfcalderoncasto9163
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
Exceptions irst
Exceptions irstExceptions irst
Exceptions irstjkumaranc
 
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#Juan Pablo
 
#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"epamspb
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 

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

More from kenbot

Grow your own tech leads
Grow your own tech leadsGrow your own tech leads
Grow your own tech leadskenbot
 
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 compositionalitykenbot
 
Responsible DI: Ditch the Frameworks
Responsible DI: Ditch the FrameworksResponsible DI: Ditch the Frameworks
Responsible DI: Ditch the Frameworkskenbot
 
FP adoption at REA
FP adoption at REAFP adoption at REA
FP adoption at REAkenbot
 
Lenses for the masses - introducing Goggles
Lenses for the masses - introducing GogglesLenses for the masses - introducing Goggles
Lenses for the masses - introducing Goggleskenbot
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programmingkenbot
 
Data made out of functions
Data made out of functionsData made out of functions
Data made out of functionskenbot
 
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 REAkenbot
 
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!kenbot
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 
The disaster of mutable state
The disaster of mutable stateThe disaster of mutable state
The disaster of mutable statekenbot
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monadskenbot
 

More from 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
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

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”.