Testing Python with the mock library

A bit ago I was writing some unit tests for a complicated code at work and when I looked at all of the crazy things I’d need to instantiate just to run this one little unit I despaired. Looking at the code it seemed like the usage of the input objects was pretty simple though, maybe, I thought, I could just write fake little stub objects to stand in for them and use those…

But then it occurred to me, that’s what mock objects are for! Mock objects are useful in unit testing as stand-ins for other functions or objects. You might use mock objects when, for example, the real thing is expensive to create, requires online resources that might sometimes be offline, or when you just want to do really fine-grained testing. With mock objects you can easily control exactly what they do and then test whether your code-under-test used the mock object correctly.

I picked the mock library as it seemed fairly straightforward and the documentation is copious, though dense. I also found the examples to not be very helpful. There are other options. All-in-all I’d recommend mock because once I got the hang of the usage it was really simple to use.

I am apparently the first person in my group to ever try to use mock objects so today I gave a lesson both on the concept of mocks and the usage of the mock library. My notebook is available:

Testing Python with the mock library

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.