Skip to main content
 首页 » 编程设计

python之重写时如何模拟基类的方法

2024年11月01日12jpfss

我有一个类似这样的代码:

from mock import MagicMock 
 
 
class Parent(object): 
 
    def test_method(self, param): 
        # do something with param 
        pass 
 
 
class Child(Parent): 
 
    def test_method(self, param): 
        # do something Child-specific with param 
        super(Child, self).test_method(param) 

现在我想确保 Child.test_method 调用 Parent.test_method。为此,我想使用 mock 中的 assert_called_once_with模块/库。但是,我想不出办法做到这一点。如果该方法不会被子类覆盖,这将很容易,正如 Need to mock out some base class behavior in a python test case 所指出的那样.但是,在我的情况下,这是相同的方法,那么我该怎么办?

请您参考如下方法:

您可以使用 patch.object :

with mock.patch.object(Parent, 'test_method') as mock_method: 
    child = Child() 
    mock_param = mock.Mock() 
    child.test_method(mock_param) 
    mock_method.assert_called_with(mock_param)