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

Yoni Tsafir yonix85 at gmail.com
Wed May 25 03:57:13 PDT 2011


OK I actually find a nice way of solving it:

def setUp(self):
    self.ret_val
    wrapper_self = self

    class MyFakeClass(Mock):
        def my_method(self):
            return wrapper_self.ret_val

    self.patcher = patch("package.MyClassName", new = MyFakeClass)
    self.patcher.start()

def tearDown(self):
    self.patcher.stop()

def test_something(self):
    self.ret_val = "xyz"
    ....

If you have a better way, please share :)

On Wed, May 25, 2011 at 1:39 PM, Yoni Tsafir <yonix85 at gmail.com> 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.
>
> 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/8aae512b/attachment.htm>


More information about the testing-in-python mailing list