Ask Your Question
1

What is the method to mock/patch a specific method inside a class?

asked 2023-06-08 10:42:20 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-08 11:06:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-08 10:42:20 +0000

Seen: 20 times

Last updated: Jun 08 '23