Ask Your Question

Revision history [back]

In Python, we can use the unittest.mock.patch method to mock/patch a specific method inside a class. Here is the basic syntax:

from unittest.mock import patch

@patch('path.to.module.ClassName.method_name')
def test_method(mock_method):
    # Test code here

This creates a patch that will replace the method_name method in the ClassName class with a mock object. In our test method, we can then use mock_method to interact with the mock object.

For example, let's say we have a class Calculator with a method add that we want to mock. We can use the following code:

from unittest.mock import patch
from calculator import Calculator

@patch('calculator.Calculator.add')
def test_add(mock_add):
    # Set up the mock
    mock_add.return_value = 10

    # Call the method and assert the result
    calculator = Calculator()
    result = calculator.add(2, 3)
    assert result == 10

In this example, we use the patch decorator to create a mock object for the add method in the Calculator class. Inside our test method, we set the return value of the mock object to 10, and then call the add method on a Calculator instance. Since the add method has been replaced with the mock object, it will return 10 instead of performing the actual addition. We then assert that the result of the add method call is 10.