mocking in python

19
An Introduction to Mocking in Python

Upload: peter-stratton

Post on 15-Apr-2017

270 views

Category:

Software


0 download

TRANSCRIPT

An Introduction to Mocking in Python

What, exactly, is a mock object?

A mock object simulates the behavior of real objects in controlled ways. - wikipedia

Test Double Taxonomy 101

Dummy - A placeholder object, unused and unusable

Fake - A working implementation that takes shortcuts

Stub - Provides default canned answers to calls

Mock - A simulated object that mimics behavior

http://martinfowler.com/articles/mocksArentStubs.html

What can mocking help to test?

Did the client code pass the parameters we expected?

Does the client code make the correct calls?

Were the calls made in the correct order?

Were the calls made the right number of times?

Example 1

test driver to mock cook: expect a hot dog order and give him this dummy hot dog in response

test driver (posing as customer) to waiter: I would like a hot dog please

waiter to mock cook: 1 hot dog please

mock cook to waiter: order up! 1 hot dog ready (gives dummy hot dog to waiter)

waiter to test driver: here is your hot dog (gives dummy hot dog to test driver)

test driver: TEST SUCCEEDED!

http://stackoverflow.com/questions/3622455/what-is-the-purpose-of-mock-objects

test driver to mock cook: expect a hot dog order and give him this dummy hot dog in response

test driver (posing as customer) to waiter: I would like a hot dog please

waiter to mock cook: 1 hamburger please

mock cook stops the test: I was told to expect a hot dog order!

test driver notes the problem: TEST FAILED! - the waiter changed the order

http://stackoverflow.com/questions/3622455/what-is-the-purpose-of-mock-objects

When should I use a Mock?The real object is slowThe real object is difficult to setupThe real object has nondeterministic behaviorThe real object does not yet existBut most importantly…The real object is NOT what you are testing

How do mock objects work?

Magic!

Almost like the real thing.

Example 2

http://www.toptal.com/python/an-introduction-to-mocking-in-python

http://www.toptal.com/python/an-introduction-to-mocking-in-python

http://www.toptal.com/python/an-introduction-to-mocking-in-python

OMFG, do I have to write these?!?

http://engineering.monsanto.com/2015/07/28/avoiding-mocks/