[TIP] How do I mock future instances of a class?

Yoni Tsafir yonix85 at gmail.com
Wed May 25 03:39:20 PDT 2011


Sorry for spamming with mock questions the last few days :)
Just doing some massive testing for complicated code.

I know that when I patch a specific method:
@patch("package.MyClassName.my_method", new = Mock(return_value="xyz"))

Even new instances of MyClass will return "xyz" as expected.

However, when I try:
@patch("package.MyClassName")
def test_something(self, my_mock):
    my_mock.my_method.return_value = "xyz"

When in code I run:
MyClassName().my_method()

I get a new different Mock and not "xyz" as I would wish.

Now, it kinda makes sense to me, but I would like to know if there's a way
around it.
Couldn't really achieve this by mocking __init__ (or maybe I did it wrong?)

Thanks!
Yoni.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110525/0c7a06d8/attachment-0001.htm>


More information about the testing-in-python mailing list