[TIP] How do I mock future instances of a class?
Yoni Tsafir
yonix85 at gmail.com
Wed May 25 23:09:32 PDT 2011
Great!
That's a much better solution :)
I think you should put it in the "Further Examples" section of the website.
Thank you very much,
Yoni.
On Wed, May 25, 2011 at 9:26 PM, Michael Foord <michael at voidspace.org.uk>wrote:
> 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.
>
>
> @patch('package.MyClassName')
> 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
> my_mock.return_value.
>
> 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.orghttp://lists.idyll.org/listinfo/testing-in-python
>
>
>
> -- http://www.voidspace.org.uk/
>
> 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/20110526/115c9e19/attachment.htm>
More information about the testing-in-python
mailing list