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

Michael Foord michael at voidspace.org.uk
Wed May 25 11:26:24 PDT 2011

On 25/05/2011 11:39, Yoni Tsafir wrote:
> 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.

Right. When you mock MyClassName then the class is replaced with a mock. 
Instances are created by *calling the class*. This means you access the 
"mock instance" by looking at the return value of the mocked class. e.g.

def test_something(self, my_mock):
     instance_mock = my_mock.return_value
     instance_mock.my_method.return_value = 'xyz'

mock autocreates a new mock to be the return value of any mock. So you 
control the behaviour of the instances of mocked classes by configuring 

All the best,

Michael Foord

> 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.
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110525/af495935/attachment.htm>

More information about the testing-in-python mailing list