Built-in Fake Objects

/29@yegor256 1
Built-in Fake Objects
Yegor Bugayenko
/29@yegor256 2
“Mock objects are
simulated objects that
mimic the behavior of
real objects in
controlled ways”
/29@yegor256 3
Fake

Objects
Mocking
Frameworks
/29@yegor256 4
static String report(User user) {
return String.format(
“Balance of %s is %d USD”,
user.profile().name(),
user.account().balance().usd()
);
}
/29@yegor256 5
interface Profile {
String name();
}
interface User {
Profile profile();
Account account();
}
interface Account {
Balance balance();
}
interface Balance {
int usd();
}
/29@yegor256 6
@Test
void printsReport() {
User user = mock(User.class);
assertThat(
Foo.report(user),
containsString(“Balance of”)
);
}
Mockito
/29@yegor256 7
@Test
void printsReport() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
doReturn(“Jeffrey”).when(account).name();
Balance balance = mock(Balance.class);
doReturn(123).when(balance).usd();
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“Balance of Jeffrey is 123 USD”)
);
}
/29@yegor256 8
1. verbosity
/29@yegor256 9
@Test
void printsReport() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
doReturn(“Jeffrey”).when(account).name();
Balance balance = mock(Balance.class);
doReturn(123).when(balance).usd();
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“Balance of Jeffrey is 123 USD”)
);
}
String report(User user) {
return String.format(
“Balance of %s is %d USD”,
user.profile().name(),
user.account().balance().usd()
);
}
/29@yegor256 10
2. code duplication
/29@yegor256 11
@Test
void reportIncludesUserName() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
doReturn(“Jeffrey”).when(account).name();
Balance balance = mock(Balance.class);
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“Jeffrey”)
);
}
@Test
void reportIncludesBalanceInUSD() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
Balance balance = mock(Balance.class);
doReturn(123).when(balance).usd();
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“123 USD”)
);
}
/29@yegor256 12
3. complexity
/29@yegor256 13
example!!
/29@yegor256 14
4. fragility
because of coupling
/29@yegor256 15
@Test
void printsReport() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
doReturn(“Jeffrey”).when(account).name();
Balance balance = mock(Balance.class);
doReturn(123).when(balance).usd();
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“Balance of Jeffrey is 123 USD”)
);
}
String report(User user) {
return String.format(
“Balance of %s is %d USD”,
user.profile().name(),
user.account().balance().usd()
);
}
/29@yegor256 16
@Test
void printsReport() {
Profile profile = mock(Profile.class);
Account account = mock(Account.class);
doReturn(“Jeffrey”).when(account).name();
Balance balance = mock(Balance.class);
doReturn(123).when(balance).usd();
doReturn(balance).when(account).balance();
User user = mock(User.class);
doReturn(profile).when(user).profile();
doReturn(account).when(user).account();
assertThat(
Foo.report(user),
containsString(“Balance of Jeffrey is 123 USD”)
);
}
String report(User user) {
return String.format(
“Balance of %s is %d USD”,
user.profile().name(),
user.account().usd()
);
}
/29@yegor256 17
“Unit tests are your
safety net”
/29@yegor256 18
false positive
/29@yegor256 19
throw-away tests
/29@yegor256 20
a solution?

fake objects!
/29@yegor256 21
interface User {
Profile profile();
Account account();
class Fake {
Fake(String name, int balance) {
// ...
}
// ...
}
}
/29@yegor256 22
@Test
void printsReport() {
User user = new User.Fake(“Jeffrey”, 123);
assertThat(
Foo.report(user),
containsString(“Balance of Jeffrey is 123 USD”)
);
}
verbosity?
/29@yegor256 23
@Test
void reportIncludesUserName() {
User user = new User.Fake(“Jeffrey”);
assertThat(
Foo.report(user),
containsString(“Jeffrey”)
);
}
code duplication?
@Test
void reportIncludesBalanceInUSD() {
User user = new User.Fake(123);
assertThat(
Foo.report(user),
containsString(“123 USD”)
);
}
/29@yegor256 24
@Test
void reportIncludesUserName() {
User user = new User.Fake(“Jeffrey”);
assertThat(
Foo.report(user),
containsString(“Jeffrey”)
);
}
complexity?
@Test
void reportIncludesBalanceInUSD() {
User user = new User.Fake(123);
assertThat(
Foo.report(user),
containsString(“123 USD”)
);
}
/29@yegor256 25
String report(User user) {
return String.format(
“Balance of %s is %d USD”,
user.profile().name(),
user.account().balance().usd()
);
}
fragility?
@Test
void reportIncludesBalanceInUSD() {
User user = new User.Fake(123);
assertThat(
Foo.report(user),
containsString(“123 USD”)
);
}
/29@yegor256 26
no throw-away tests
any more
/29@yegor256 27
always ship them

together!
/29@yegor256 28
interface User {
Profile profile();
Account account();
class Fake {
}
}
class UserTest {
@Test
void hasBalance() {
User user = new User.Fake(123);
assertThat(
user.account().balance().usd(),
not(equalTo(0))
);
}
}
/29@yegor256 29
Fake

Objects
Mocking
Frameworks
/29@yegor256 30
Section 2.8
Don’t mock; use fakes
1 of 30

Recommended

The Human Linter by
The Human LinterThe Human Linter
The Human LinterIlya Gelman
389 views49 slides
11. delete record by
11. delete record11. delete record
11. delete recordRazvan Raducanu, PhD
192 views4 slides
10. view one record by
10. view one record10. view one record
10. view one recordRazvan Raducanu, PhD
129 views5 slides
14. CodeIgniter adaugarea inregistrarilor by
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilorRazvan Raducanu, PhD
12 views9 slides
12. edit record by
12. edit record12. edit record
12. edit recordRazvan Raducanu, PhD
616 views3 slides
7. copy1 by
7. copy17. copy1
7. copy1Razvan Raducanu, PhD
84 views12 slides

More Related Content

What's hot

8. vederea inregistrarilor by
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilorRazvan Raducanu, PhD
192 views16 slides
Drupal 9 training ajax by
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajaxNeelAndrew
531 views16 slides
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app... by
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
77.7K views38 slides
Angular 2 Architecture (Bucharest 26/10/2016) by
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Eyal Vardi
4.1K views43 slides
Angular 2.0 forms by
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
3.4K views38 slides
Crash Course to SQL in PHP by
Crash Course to SQL in PHPCrash Course to SQL in PHP
Crash Course to SQL in PHPwebhostingguy
252 views6 slides

What's hot(12)

Drupal 9 training ajax by NeelAndrew
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajax
NeelAndrew531 views
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app... by Dan Wahlin
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Dan Wahlin77.7K views
Angular 2 Architecture (Bucharest 26/10/2016) by Eyal Vardi
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi4.1K views
Angular 2.0 forms by Eyal Vardi
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi3.4K views
Crash Course to SQL in PHP by webhostingguy
Crash Course to SQL in PHPCrash Course to SQL in PHP
Crash Course to SQL in PHP
webhostingguy252 views
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv... by sriram sarwan
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
sriram sarwan51 views
Exemple de création de base by Saber LAJILI
Exemple de création de baseExemple de création de base
Exemple de création de base
Saber LAJILI539 views
Http Communication in Angular 2.0 by Eyal Vardi
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
Eyal Vardi2.8K views
WordCamp Denver 2012 - Custom Meta Boxes by Jeremy Green
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
Jeremy Green1.4K views

Viewers also liked

ORM is a perfect anti-pattern by
ORM is a perfect anti-patternORM is a perfect anti-pattern
ORM is a perfect anti-patternYegor Bugayenko
2.3K views10 slides
How Anemic Objects Kill OOP by
How Anemic Objects Kill OOPHow Anemic Objects Kill OOP
How Anemic Objects Kill OOPYegor Bugayenko
2K views16 slides
Object Oriented Lies by
Object Oriented LiesObject Oriented Lies
Object Oriented LiesYegor Bugayenko
2.4K views13 slides
Java vs OOP by
Java vs OOPJava vs OOP
Java vs OOPYegor Bugayenko
2.2K views27 slides
Who Is a Software Architect? by
Who Is a Software Architect?Who Is a Software Architect?
Who Is a Software Architect?Yegor Bugayenko
1.2K views9 slides
Management without managers by
Management without managersManagement without managers
Management without managersYegor Bugayenko
1K views14 slides

Viewers also liked(20)

ORM is a perfect anti-pattern by Yegor Bugayenko
ORM is a perfect anti-patternORM is a perfect anti-pattern
ORM is a perfect anti-pattern
Yegor Bugayenko2.3K views
eXtremely Distributed Software Development by Yegor Bugayenko
eXtremely Distributed Software DevelopmenteXtremely Distributed Software Development
eXtremely Distributed Software Development
Yegor Bugayenko362 views
How Do You Talk to Your Microservice? by Yegor Bugayenko
How Do You Talk to Your Microservice?How Do You Talk to Your Microservice?
How Do You Talk to Your Microservice?
Yegor Bugayenko1.9K views
ORM is an Offensive Anti-Pattern by Yegor Bugayenko
ORM is an Offensive Anti-PatternORM is an Offensive Anti-Pattern
ORM is an Offensive Anti-Pattern
Yegor Bugayenko1.4K views
Need It Robust? Make It Fragile! by Yegor Bugayenko
Need It Robust? Make It Fragile!Need It Robust? Make It Fragile!
Need It Robust? Make It Fragile!
Yegor Bugayenko1.7K views
How Do You Know When Your Product is Ready to be Shipped? by Yegor Bugayenko
How Do You Know When Your Product is Ready to be Shipped?How Do You Know When Your Product is Ready to be Shipped?
How Do You Know When Your Product is Ready to be Shipped?
Yegor Bugayenko1.1K views
How Much Immutability Is Enough? by Yegor Bugayenko
How Much Immutability Is Enough?How Much Immutability Is Enough?
How Much Immutability Is Enough?
Yegor Bugayenko1.7K views
Practical Example of AOP with AspectJ by Yegor Bugayenko
Practical Example of AOP with AspectJPractical Example of AOP with AspectJ
Practical Example of AOP with AspectJ
Yegor Bugayenko1.4K views

Similar to Built-in Fake Objects

Creating an Uber Clone - Part XXXX.pdf by
Creating an Uber Clone - Part XXXX.pdfCreating an Uber Clone - Part XXXX.pdf
Creating an Uber Clone - Part XXXX.pdfShaiAlmog1
626 views17 slides
Юрий Буянов «Squeryl — ORM с человеческим лицом» by
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»e-Legion
897 views34 slides
Drupal csu-open atriumname by
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumnameEmanuele Quinto
1.1K views34 slides
Teste de Integração com DbUnit e jIntegrity by
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
1.6K views48 slides
Symfony2 Building on Alpha / Beta technology by
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
750 views59 slides
Doctrine For Beginners by
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
1.5K views69 slides

Similar to Built-in Fake Objects(20)

Creating an Uber Clone - Part XXXX.pdf by ShaiAlmog1
Creating an Uber Clone - Part XXXX.pdfCreating an Uber Clone - Part XXXX.pdf
Creating an Uber Clone - Part XXXX.pdf
ShaiAlmog1626 views
Юрий Буянов «Squeryl — ORM с человеческим лицом» by e-Legion
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
e-Legion897 views
Teste de Integração com DbUnit e jIntegrity by Washington Botelho
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho1.6K views
Symfony2 Building on Alpha / Beta technology by Daniel Knell
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell750 views
Doctrine For Beginners by Jonathan Wage
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage1.5K views
Being Functional on Reactive Streams with Spring Reactor by Max Huang
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring Reactor
Max Huang296 views
Creating a Facebook Clone - Part XXV.pdf by ShaiAlmog1
Creating a Facebook Clone - Part XXV.pdfCreating a Facebook Clone - Part XXV.pdf
Creating a Facebook Clone - Part XXV.pdf
ShaiAlmog1251 views
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation" by epamspb
#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"
epamspb106 views
Clean Code: Chapter 3 Function by Kent Huang
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang5.4K views
Android Testing by Evan Lin
Android TestingAndroid Testing
Android Testing
Evan Lin3.2K views
Intro programacion funcional by NSCoder Mexico
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
NSCoder Mexico306 views

More from Yegor Bugayenko

Can Distributed Teams Deliver Quality? by
Can Distributed Teams Deliver Quality?Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?Yegor Bugayenko
269 views23 slides
Are You Sure You Are Not a Micromanager? by
Are You Sure You Are Not a Micromanager?Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?Yegor Bugayenko
245 views16 slides
On Requirements Management (Demotivate Them Right) by
On Requirements Management (Demotivate Them Right)On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)Yegor Bugayenko
220 views16 slides
My Experience of 1000 Interviews by
My Experience of 1000 InterviewsMy Experience of 1000 Interviews
My Experience of 1000 InterviewsYegor Bugayenko
219 views20 slides
Are you sure you are not a micromanager? by
Are you sure you are not a micromanager?Are you sure you are not a micromanager?
Are you sure you are not a micromanager?Yegor Bugayenko
251 views15 slides
Quality Assurance vs. Testing by
Quality Assurance vs. TestingQuality Assurance vs. Testing
Quality Assurance vs. TestingYegor Bugayenko
660 views25 slides

More from Yegor Bugayenko(20)

Can Distributed Teams Deliver Quality? by Yegor Bugayenko
Can Distributed Teams Deliver Quality?Can Distributed Teams Deliver Quality?
Can Distributed Teams Deliver Quality?
Yegor Bugayenko269 views
Are You Sure You Are Not a Micromanager? by Yegor Bugayenko
Are You Sure You Are Not a Micromanager?Are You Sure You Are Not a Micromanager?
Are You Sure You Are Not a Micromanager?
Yegor Bugayenko245 views
On Requirements Management (Demotivate Them Right) by Yegor Bugayenko
On Requirements Management (Demotivate Them Right)On Requirements Management (Demotivate Them Right)
On Requirements Management (Demotivate Them Right)
Yegor Bugayenko220 views
My Experience of 1000 Interviews by Yegor Bugayenko
My Experience of 1000 InterviewsMy Experience of 1000 Interviews
My Experience of 1000 Interviews
Yegor Bugayenko219 views
Are you sure you are not a micromanager? by Yegor Bugayenko
Are you sure you are not a micromanager?Are you sure you are not a micromanager?
Are you sure you are not a micromanager?
Yegor Bugayenko251 views
Zold: a cryptocurrency without Blockchain by Yegor Bugayenko
Zold: a cryptocurrency without BlockchainZold: a cryptocurrency without Blockchain
Zold: a cryptocurrency without Blockchain
Yegor Bugayenko282 views
How to Cut Corners and Stay Cool by Yegor Bugayenko
How to Cut Corners and Stay CoolHow to Cut Corners and Stay Cool
How to Cut Corners and Stay Cool
Yegor Bugayenko318 views

Recently uploaded

tecnologia18.docx by
tecnologia18.docxtecnologia18.docx
tecnologia18.docxnosi6702
5 views5 slides
The Path to DevOps by
The Path to DevOpsThe Path to DevOps
The Path to DevOpsJohn Valentino
5 views6 slides
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Marc Müller
42 views83 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
12 views16 slides
Unleash The Monkeys by
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
8 views28 slides
Quality Engineer: A Day in the Life by
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the LifeJohn Valentino
6 views18 slides

Recently uploaded(20)

tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller42 views
Quality Engineer: A Day in the Life by John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino6 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 views
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j12 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ8 views
Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app8 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri890 views

Built-in Fake Objects

  • 1. /29@yegor256 1 Built-in Fake Objects Yegor Bugayenko
  • 2. /29@yegor256 2 “Mock objects are simulated objects that mimic the behavior of real objects in controlled ways”
  • 4. /29@yegor256 4 static String report(User user) { return String.format( “Balance of %s is %d USD”, user.profile().name(), user.account().balance().usd() ); }
  • 5. /29@yegor256 5 interface Profile { String name(); } interface User { Profile profile(); Account account(); } interface Account { Balance balance(); } interface Balance { int usd(); }
  • 6. /29@yegor256 6 @Test void printsReport() { User user = mock(User.class); assertThat( Foo.report(user), containsString(“Balance of”) ); } Mockito
  • 7. /29@yegor256 7 @Test void printsReport() { Profile profile = mock(Profile.class); Account account = mock(Account.class); doReturn(“Jeffrey”).when(account).name(); Balance balance = mock(Balance.class); doReturn(123).when(balance).usd(); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“Balance of Jeffrey is 123 USD”) ); }
  • 9. /29@yegor256 9 @Test void printsReport() { Profile profile = mock(Profile.class); Account account = mock(Account.class); doReturn(“Jeffrey”).when(account).name(); Balance balance = mock(Balance.class); doReturn(123).when(balance).usd(); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“Balance of Jeffrey is 123 USD”) ); } String report(User user) { return String.format( “Balance of %s is %d USD”, user.profile().name(), user.account().balance().usd() ); }
  • 10. /29@yegor256 10 2. code duplication
  • 11. /29@yegor256 11 @Test void reportIncludesUserName() { Profile profile = mock(Profile.class); Account account = mock(Account.class); doReturn(“Jeffrey”).when(account).name(); Balance balance = mock(Balance.class); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“Jeffrey”) ); } @Test void reportIncludesBalanceInUSD() { Profile profile = mock(Profile.class); Account account = mock(Account.class); Balance balance = mock(Balance.class); doReturn(123).when(balance).usd(); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“123 USD”) ); }
  • 15. /29@yegor256 15 @Test void printsReport() { Profile profile = mock(Profile.class); Account account = mock(Account.class); doReturn(“Jeffrey”).when(account).name(); Balance balance = mock(Balance.class); doReturn(123).when(balance).usd(); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“Balance of Jeffrey is 123 USD”) ); } String report(User user) { return String.format( “Balance of %s is %d USD”, user.profile().name(), user.account().balance().usd() ); }
  • 16. /29@yegor256 16 @Test void printsReport() { Profile profile = mock(Profile.class); Account account = mock(Account.class); doReturn(“Jeffrey”).when(account).name(); Balance balance = mock(Balance.class); doReturn(123).when(balance).usd(); doReturn(balance).when(account).balance(); User user = mock(User.class); doReturn(profile).when(user).profile(); doReturn(account).when(user).account(); assertThat( Foo.report(user), containsString(“Balance of Jeffrey is 123 USD”) ); } String report(User user) { return String.format( “Balance of %s is %d USD”, user.profile().name(), user.account().usd() ); }
  • 17. /29@yegor256 17 “Unit tests are your safety net”
  • 21. /29@yegor256 21 interface User { Profile profile(); Account account(); class Fake { Fake(String name, int balance) { // ... } // ... } }
  • 22. /29@yegor256 22 @Test void printsReport() { User user = new User.Fake(“Jeffrey”, 123); assertThat( Foo.report(user), containsString(“Balance of Jeffrey is 123 USD”) ); } verbosity?
  • 23. /29@yegor256 23 @Test void reportIncludesUserName() { User user = new User.Fake(“Jeffrey”); assertThat( Foo.report(user), containsString(“Jeffrey”) ); } code duplication? @Test void reportIncludesBalanceInUSD() { User user = new User.Fake(123); assertThat( Foo.report(user), containsString(“123 USD”) ); }
  • 24. /29@yegor256 24 @Test void reportIncludesUserName() { User user = new User.Fake(“Jeffrey”); assertThat( Foo.report(user), containsString(“Jeffrey”) ); } complexity? @Test void reportIncludesBalanceInUSD() { User user = new User.Fake(123); assertThat( Foo.report(user), containsString(“123 USD”) ); }
  • 25. /29@yegor256 25 String report(User user) { return String.format( “Balance of %s is %d USD”, user.profile().name(), user.account().balance().usd() ); } fragility? @Test void reportIncludesBalanceInUSD() { User user = new User.Fake(123); assertThat( Foo.report(user), containsString(“123 USD”) ); }
  • 27. /29@yegor256 27 always ship them
 together!
  • 28. /29@yegor256 28 interface User { Profile profile(); Account account(); class Fake { } } class UserTest { @Test void hasBalance() { User user = new User.Fake(123); assertThat( user.account().balance().usd(), not(equalTo(0)) ); } }