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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-08 10:42:20 +0000
Seen: 20 times
Last updated: Jun 08 '23
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?