[英]Python Mock - check if method was called from another class?
How can I check if method is called inside another method, when those methods are from different classes? 当这些方法来自不同的类时,如何检查方法是否在另一个方法内调用?
If they are from same class, I can do this: 如果它们来自同一班级,我可以这样做:
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()
But if method_a
would be from different class, then it would raise AssertionError
that it was not called. 但是,如果method_a
来自不同的类,那么它将引发AssertionError
而不被调用。
How could I do same check if I would have these classes instead (and I want to check if method_b
calls method_a
)?: 我该如何做同样的检查,是否需要这些类(并且我想检查method_b
调用method_a
)?
class A():
def method_a(self):
pass
class B():
def method_b(self):
A().method_a()
You have to simply stub A
within the same context as B
, and validate against the way it would have been called. 您只A
在与B
相同的上下文中对A
进行存根,并根据其调用方式进行验证。 Example: 例:
>>> 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.