Thursday, September 17, 2015

Patching a python class attribute in a unit test using mock

I often want to change a class attribute in a unit test. While it is sort of documented in the official documentation, it's missing an actual example of this use case. So say you have a class:
class MyClass(object):
  myattr = 1
and you want to test the functionality of the class, but need to change the value of myattr from the default:
import mock
import modulename

with mock.patch.object(modulename.MyClass, "myattr", new=50):
  # do test stuff

No comments: