Search code examples
pythonmockingpython-unittestmagicmock

How to test if another class method is called within a method in python?


I have the following structure:

ClassB():
   def foo():

Class A():
   def __init__(self, B):
       #some initialisations
   def method1():
       #complex logic
       B.foo()

I am trying to write a unit test method1 and would like to test if foo is called once or not. How I can achieve this? What should I mock?


Solution

  • You should create a Mock for B, pass it to the constructor of A and check if the function was called once.

    You can write the Mock by yourself. E.g.:

    class B_Mock():
        def __init__(self):
           self.foo_calls = 0
    
        def foo(self):
            self.foo_calls += 1
    

    And than check the attr foo_calls of your B_Mock instance with assert