简体   繁体   English

Python Mock-检查方法是否从另一个类调用?

[英]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.

相关问题 如何使用 pytest_mock 模拟从另一个类调用的类方法 - How to mock a class method that is called from another class with pytest_mock 在另一个 function 中调用的模拟 class 方法 - Mock class method that is called within another function Python 模拟:如何模拟从正在测试的 class 方法调用的 class - Python mock: How to mock a class being called from the class method being tested Python,如果从另一个 class 调用方法,则无法断言 - Python, can't assert if method called from another class Python unittest模拟方法在另一个模块中调用时出错 - Python unittest mock method which called in another module work error Python unittest.mock:调用了已修补的类方法,但断言失败 - Python unittest.mock: patched class method called but assertion fails python:强制只从另一个类方法中调用一个类方法? - python: enforce that a class method is only called from within another class method? Python:当从另一个类中调用初始方法时,类方法调用其他类方法 - Python: class methods calling other class methods when initial method is called from within another class Python 单元测试:模拟外部库 function 从 class ZA8CFDE6331BD1C49EB2AC96F8691 调用 - Python unittest: Mock an external library function called from a class object 使用Python单元测试库(unittest,mock),如何断言是否在类A的方法内调用了类B的方法? - Using Python unittesting libraries (unittest, mock), how to assert if a method of class B was called within a method of class A?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM