Mocking properties in Python

24 Jun 2016

It doesn’t happen all that often, but sometimes when writing unit tests you want to mock a property and specify a return value. The mock library provides a PropertyMock for that, but using it probably doesn’t work the way you would initially think it would.

I had this exact problem earlier this week and had to explain it to two different people in the two days after that. So why not write it down in a blog post?

Suppose you have this silly implementation of a class that takes a file path and reads the file’s content into a variable that can be accessed through a property: