简体   繁体   中英

How to mock an inherited, collaborating method in Python

I've got a setup similar to this.

class A:
    def send_it(some_data):
        data = {}
        ....fill data
        send('url',data)


class B(A):
    def do_real_work():
        ... do stuff
        self.send_it(some_data)`

My goal is to test B.do_real_work().

What I would like to do is mock the b.send_it() method with a custom implementation that would allow me to assign the data object to some global or instance variable so that it can be inspected.

I haven't been able to figure out how to mock a method (send_it()) when actually testing the do_real_work() method.

You can apply a mock into methods being called.

from unittest.mock import MagicMock
b = B()

b.send_it = MagicMock()

b.do_real_work() # It calls MagicMock() instead of A.send_it()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM