[英]How to mock a class method that is called from another class with pytest_mock
[英]Python Mock - check if method was called from another class?
当这些方法来自不同的类时,如何检查方法是否在另一个方法内调用?
如果它们来自同一班级,我可以这样做:
from unittest import mock
class A():
def method_a(self):
pass
def method_b(self):
self.method_a()
a = A()
a.method_a = mock.MagicMock()
a.method_b()
a.method_a.assert_called_once_with()
但是,如果method_a
来自不同的类,那么它将引发AssertionError
而不被调用。
我该如何做同样的检查,是否需要这些类(并且我想检查method_b
调用method_a
)?
class A():
def method_a(self):
pass
class B():
def method_b(self):
A().method_a()
您只A
在与B
相同的上下文中对A
进行存根,并根据其调用方式进行验证。 例:
>>> class B():
... def method_b(self):
... A().method_a()
...
>>> A = mock.MagicMock()
>>> A().method_a.called
False
>>> b = B()
>>> b.method_b()
>>> A().method_a.called
True
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.