简体   繁体   中英

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.

How could I do same check if I would have these classes instead (and I want to check if method_b calls 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. 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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM