需要在 python 测试用例中模拟一些基类行为 [英] Need to mock out some base class behavior in a python test case

查看:40
本文介绍了需要在 python 测试用例中模拟一些基类行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的标题相当具有描述性,但这里是.假设我有这个设置.

My title is fairly descriptive, but here goes. Suppose I have this setup.

class BaseClass(object):
    def __init__(self):
        pass
    def base_function(self, param="Hello World"):
        print param

#multiple inheritance probably irrelevant but my problem deals with it
class DerivedClass(BaseClass, AnotherBaseClass):
    def __init__(self):
        pass
    def advanced_function(self):
        #blah blah blah
        #code code code
        self.base_function()

现在,我在测试派生类的情况下,但这样做时,我需要确保它的基类方法被调用.我尝试做这样的事情

Now, I have a situation where I am testing a derived class, but in doing so, I need to ensure that it's base class methods are called. I tried doing something like this

from mock import MagicMock

d = DerivedClass()
super(DerivedClass, d).base_function = MagicMock()
d.advanced_function()
super(DerivedClass, d).base_function.assert_called()

我 100% 确定这个设置是错误的,因为

I'm 100% sure this setup is wrong, because

AttributeError: 'super' object has no attribute 'base_function'

我知道我在使用 super 时做错了什么,有人知道吗?

I know I'm doing something wrong with super, anyone have an idea?

推荐答案

通过 BaseClass.base_function 访问.由于您没有重载该方法,您只需继承它,DerivedClass.base_function 是同一个对象:

Access via BaseClass.base_function. As you don't overload the method, you just inherit it, the DerivedClass.base_function is the same object:

id(BaseClass.base_function) == id(DerivedClass.base_function)

创建实例时,它们会继承模拟.

When the instances are created, they inherit the mock.

这篇关于需要在 python 测试用例中模拟一些基类行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆