Search code examples
pythonunit-testingddt

Python Unittest: make sure patched class is called


I have the following code

@ddt
@patch('mymodule.myclass', MagicMock)
class MyTest(): 
    @data([val1, val2])
    @unpack 
    def test_run(self, val1, val2):
         ClassA().run(val1, val2)  

How Do I assert some methods inside mymodule.myclass are called?


Solution

  • When you patch it at the class level you get a reference to the mock as an argument in your test methods, for instance:

    @ddt
    @patch('mymodule.myclass', MagicMock)
    class MyTest(): 
        @data([val1, val2])
        @unpack 
        def test_run(self, val1, val2, my_class_mock):
             # use my_class_mock   
    

    You can use this mock for many purposes but in this case you'd still need to patch your class inside the test method to make your assertions.