Search code examples
pythonpython-3.xunit-testingpython-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.

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()

Solution

  • 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
    >>>