How to assert that a method was called in a unit test in Python

Asserting that a method was called in a unit test raises an assertion error if a method is not called.

Solution for How to assert that a method was called in a unit test in Python : You can use unittest.mock.Mock.assert_called() to assert that a method was called To assert a method module.func is called in a unit test method, first patch the object into the method by adding the decorator @unittest.mock.patch.object(module, “func”) immediately before defining the unit test method. Add another parameter to the unit test method. When the unit test method is called, a unittest.mock.Mock object imitating module.func will be passed into the last parameter of the unit test method. To assert that module.func is called, call unittest.mock.Mock.assert_called() on the previously created unittest.mock.Mock object in the body of the unit test method. If module.func is called anywhere in the method, the assertion will pass and the method will complete. Otherwise, the assertion will fail and an error will be printed.


how-to-assert-that-a-method-was-called-in-a-unit-test-in-python