简体   繁体   English

如何在Python中模拟继承的协作方法

[英]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(). 我的目标是测试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. 我想做的是使用自定义实现模拟b.send_it()方法,该实现允许我将数据对象分配给某些全局变量或实例变量,以便可以对其进行检查。

I haven't been able to figure out how to mock a method (send_it()) when actually testing the do_real_work() method. 在实际测试do_real_work()方法时,我还无法弄清楚如何模拟方法(send_it())。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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