SlideShare a Scribd company logo
Intro To Mocking:
Why Unit Testing Doesn’t Have to
Be So Hard!
Daniel Davis
@Ooblioob
• Software Developer for 8 years
• Senior Consultant: Excella Consulting in
Washington, DC
• Fun Fact:
– I ran the “Jingle All The Way” 5k dressed as a
Giant Gingerbread man
A Little About Me…
3
Survey Time!
4
• Struggled with unit testing until I learned
about Mocking
Learning To Test
5
Me Learning about Mocking…
6
Image credit: http://stylecaster.com/excited-gif/
Many of us are in the same
boat…
7
• “I wish someone would just give a talk on
this…”
• So if that’s you…
We all want to write better tests…
Let’s Talk About
Unit Tests…
Unit – 70%
Integration
– 20%
UI
10%
Testing Types
• “They’re good when the problem is easy”
– A rabbit hole of testing
• “I spend too much time writing lots of code
to test, so I give up”
• “There’s just some stuff you can’t unit test”
Great Unit Testing Myths
Mocking makes unit
testing easier!
12
What Are Mocks?
13
Test Double
Dummy
Object
Test Stub Test Spy
Mock
Object
Fake
Object
Commonly referred to as “Mocks”
• Stubs
– Provide a canned response to method calls
• Spy
– Real objects that behave like normal except
when a specific condition is met
• Mocks
– Verifies behavior (calls) to a method
What Are Mocks?
14
Blah Blah Blah professor Dan…
15
• Eliminates dependencies
– Isolated Unit Tests
Problems Mocks Solve
16
foo(x) bar(x)
• Tests methods that have no return value
Problems Mocks Solve
17
How do we know that bar(x) has been called?
• Tests error handling
Problems Mocks Solve
18
• Eliminate dependency on database calls
– Speed up testing!
• Reduce test complexity
– Don’t have to write complex logic to handle
behavior of methods not under test
• Don’t have to wait to implement other
methods
Other Reasons Mocks Are Important
19
Ok, I’m sold…
Show me how to actually do this…
20
• Mock (MagicMock)
– Most robust, popular
– Built-in as of Python 3.3!
• flexmock
– Based on Ruby’s flexmock
• mox
– Similar to Java’s EasyMock
• Mocker
• dingus
– “record then assert” mocking library
• fudge
– Similar to Mockito
• MiniMock
– Simple mocking with DocTest
What Are The Python Options?
21
Sample Problem
22
Problem:
Tinder Competitor
True love is an isolated
container…
Image Credits:
- http://www.forbes.com/sites/jjcolao/2013/04/08/tinder-for-business-dating-app-looks-to-conquer-other-matchmaking-verticals/
- https://blog.docker.com
• Create a method to return a new, random
victim candidate
– Must not show the same person
– Must not show someone the user has already
“swiped” on
Problem: “Docker” dating app
Easy enough…
25
“Surely no one could
have seen EVERYONE
in the database!!!”
- The Intern
get_next_person() get_random_person()
Write a Unit Test…
26
It works!!!
27
Noooooooooo!!!!
29
Easy enough…
30
What if knew the result of get_random_person()???
31
Patching
Module.attribute
Mock method
It works EVERY SINGLE TIME!!!
33
Variations on a theme
34
Variations on a theme
35
Variations on a theme
36
Variations on a theme
37
OMG, ContextManagers! WHAT???
But what if we call it
multiple times???
38
• What if I want to test the while loop?
Different results on multiple calls
Uh…umm…
40
UMM…
Use side_effect
41
• Use patching / mocks to bring certainty to
method calls
• Eliminates dependencies on other code
– Even unfinished code!!!
• Lots of ways to do it, pick your favorite
Recap: What did we learn?
42
Mocking to Verify Behavior
43
Problem:
Matching in “Docker”
• When a user swipes right…
• If the other user “likes” them:
– Send them both a message with contact info
• If the other user “dislikes” them:
– Let the user down gently…
• If the other user hasn’t evaluated yet:
– Display the “give it time” message
Problem: “Docker” matches
Implementation
46
How do we test this??? No return values!!!
Behavior Verification
47
What about checking
parameters???
48
Verifying Parameters
49
Shouldn’t we check the other
methods too?
50
We’d need to have multiple mocks to do that!!!
Multiple Mocks
51
Patch Multiple
52
Testing Multiple Calls…
53
Multiple calls
54
Whew!!!
Almost Done!
The day is almost over!
You can sleep later!
Image Credits:
- http://www.clickhole.com/article/8-kittens-god-forbid-could-be-used-prop-wobbly-tab-1364
- http://stuffpoint.com/dogs/image/208632/adorable-corgi-puppies-running-ddddd-picture/
Mocking
Exceptions
56
Sample Problem:
Docker Payments with Stripe
Stripe Payment Code
Stripe Testing…ugh!
59
• Requires us to call the API
• Unclear what those numbers mean
• Must create the stripe_token
– Not a dictionary of CC fields
– Encrypted
That’s ridiculous…
60
There’s got to be a better way…
…have you tried Mocking???
61
Mocking an Exception
62
Wrap Up:
Key Take-Aways
63
• Mocking makes writing unit tests simpler
– Eliminates dependencies
– Verifies behavior
– Tests error handling
• You just need some practice!
Remember This!
• http://mock.readthedocs.org/en/latest/
• Pip Install Mock (Python 2)
• Create a simple class, then write tests!
Try It On Your Own
65
Let’s Go Write
Some Tests!!!
66
Questions?
67
GitHub: https://github.com/Ooblioob
Twitter: @Ooblioob

More Related Content

KEY
Overview of Testing Talks at Pycon
PPTX
The importance of testing in a web design & build project
KEY
It's Not Just About Code
PDF
Vale2017 b13-presentation
PPTX
Creating a Lawyer in a Box: Building User Friendly Guided Interviews with Doc...
PPT
Don’t make me think!
PPTX
Mocking in python
PPTX
Type mock isolator
Overview of Testing Talks at Pycon
The importance of testing in a web design & build project
It's Not Just About Code
Vale2017 b13-presentation
Creating a Lawyer in a Box: Building User Friendly Guided Interviews with Doc...
Don’t make me think!
Mocking in python
Type mock isolator

Similar to Intro to Mocking - DjangoCon 2015 (20)

PPTX
Mocking in Python
PPTX
Unit testing and mocking in Python - PyCon 2018 - Kenya
PPT
Python testing
ODP
Automated Testing in Django
PDF
Just Mock It - Mocks and Stubs
PDF
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
PDF
CBDW2014 - MockBox, get ready to mock your socks off!
PDF
[PyCon2016]To mock or not to mock, that is the questions
PDF
Python testing using mock and pytest
KEY
Testing w-mocks
PDF
Managing Mocks
PDF
Summit 16: Stop Writing Legacy Code!
PPTX
Making a Mock by Kelsey Shannahan
PDF
Mock Introduction
PPTX
Unit tests and mocks
PPTX
Mocking
PDF
Python Mock Object Library: Common Pitfalls and Best Practices - Sunaina Pai ...
PPTX
Unit Testing And Mocking
PDF
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
PDF
TDD in Python With Pytest
Mocking in Python
Unit testing and mocking in Python - PyCon 2018 - Kenya
Python testing
Automated Testing in Django
Just Mock It - Mocks and Stubs
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
CBDW2014 - MockBox, get ready to mock your socks off!
[PyCon2016]To mock or not to mock, that is the questions
Python testing using mock and pytest
Testing w-mocks
Managing Mocks
Summit 16: Stop Writing Legacy Code!
Making a Mock by Kelsey Shannahan
Mock Introduction
Unit tests and mocks
Mocking
Python Mock Object Library: Common Pitfalls and Best Practices - Sunaina Pai ...
Unit Testing And Mocking
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
TDD in Python With Pytest
Ad

More from Excella (20)

PDF
DCSUG - What's Really Going On? Observer Worksheet
PDF
DCSUG - We Are The Leaders We Have Been Waiting For by Lyssa Adkins
PDF
DCSUG - Servant Leadership Handout
PDF
DCSUG - Servant Leadership
PDF
DCSUG - Applying Analysis in an Agile World
PDF
DCSUG - The Art and Practice of the Agile Leader
PPTX
DCSUG - Finding Lean in Agile
PDF
DCSUG - Impact Mapping
PDF
DCSUG - Happiness: A Key Component of Agile
PPTX
The Awkward Teenager of Testing
PDF
Let's Sharpen Your Agile Ax, It's Story Splitting Time
PDF
Managing for Happiness by Jurgen Appelo at DCSUG on 8/9/2016
PDF
The 7 Secrets of Highly Effective Retrospectives (DCSUG)
PPTX
Get Your Productivity Game On!!
PPTX
How to Structure Multi Team Organizations
PPTX
Tactics to Kickstart Your Journey Toward DevOps
PPTX
Tactics to Kickstart Your Journey Toward Continuous Delivery
PPTX
Using ansible vault to protect your secrets
PDF
Using Lean Thinking to Increase the Value of Agile
PPTX
What does it mean to be Lean
DCSUG - What's Really Going On? Observer Worksheet
DCSUG - We Are The Leaders We Have Been Waiting For by Lyssa Adkins
DCSUG - Servant Leadership Handout
DCSUG - Servant Leadership
DCSUG - Applying Analysis in an Agile World
DCSUG - The Art and Practice of the Agile Leader
DCSUG - Finding Lean in Agile
DCSUG - Impact Mapping
DCSUG - Happiness: A Key Component of Agile
The Awkward Teenager of Testing
Let's Sharpen Your Agile Ax, It's Story Splitting Time
Managing for Happiness by Jurgen Appelo at DCSUG on 8/9/2016
The 7 Secrets of Highly Effective Retrospectives (DCSUG)
Get Your Productivity Game On!!
How to Structure Multi Team Organizations
Tactics to Kickstart Your Journey Toward DevOps
Tactics to Kickstart Your Journey Toward Continuous Delivery
Using ansible vault to protect your secrets
Using Lean Thinking to Increase the Value of Agile
What does it mean to be Lean
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Getting Started with Data Integration: FME Form 101
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
A Presentation on Artificial Intelligence
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
A comparative analysis of optical character recognition models for extracting...
PPT
Teaching material agriculture food technology
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Big Data Technologies - Introduction.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Getting Started with Data Integration: FME Form 101
Unlocking AI with Model Context Protocol (MCP)
Machine learning based COVID-19 study performance prediction
Group 1 Presentation -Planning and Decision Making .pptx
Encapsulation_ Review paper, used for researhc scholars
Spectral efficient network and resource selection model in 5G networks
A Presentation on Artificial Intelligence
Per capita expenditure prediction using model stacking based on satellite ima...
A comparative analysis of optical character recognition models for extracting...
Teaching material agriculture food technology
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
Machine Learning_overview_presentation.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Big Data Technologies - Introduction.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Mobile App Security Testing_ A Comprehensive Guide.pdf

Intro to Mocking - DjangoCon 2015