[TIP] How do I mock future instances of a class?
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:
> def test_something(self, my_mock):
> my_mock.my_method.return_value = "xyz"
> When in code I run:
> 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,
> 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
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
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...
More information about the testing-in-python