class A(object):
def get_value(self):
return "foo"
class B(A):
def get_value(self):
value = super(B, self).get_value()
value + "bar"
return value
鉴于上述类,当我想为该类编写测试套件时B()
,我该如何模拟对方法super()
的调用?我想要的伪代码是:A()``get_value()
class BTestCase(TestCase):
def setUp(self):
self.b = B()
def test_get_value(self):
# This won't work, attribute error- "super" object has
# no attribute get_value
super(B, self.b).get_value = Mock()
super(B, self.b).get_value.assert_called_once_with()
但显然这行不通。但我想知道是否有办法测试该调用,以及修补是否是解决问题的方法。
来自文档(http://docs.python.org/2/library/functions.html#super)
super(type[, object-or-type])
返回一个代理对象,该代理对象将方法调用委托给类型的父类或兄弟类。这对于访问类中已被重写的继承方法很有用。搜索顺序与 getattr() 使用的顺序相同,只是跳过了类型本身。<…>
super 有两种典型的用例。
__
换句话说,super
是一个用于获取方法和属性的类,而不是用于设置它们的类。
如果您想要对某些内容进行 monkey-patch,请直接使用实例或类:
class A(object): ...
class B(A): ...
b = B()
super(B, b).get_value = Something() # no
b.get_value = Something() # ok
B.get_value = Something() # ok
A.get_value = Something() # ok