At first itβs very important to understand that you always need a Mock, where this is what you are trying to mock, it is used as indicated in the unittest.mock documentation.
The basic principle is that you correct where the object is viewed, which does not necessarily coincide with the place where it is defined.
Next, you will need to return an instance of MagicMock as the return_value fixed object. So, to summarize this, you will need to use the following sequence.
- Patch object
- Prepare
MagicMock for use - return the
MagicMock we just created as return_value
Here is a brief example of a project.
connection.py (the class we would like to execute Mock)
class Connection(object): def execute(self): return "Connection to server made"
file.py (where the class is used)
from project.connection import Connection class FileRemoveOp(object): def __init__(self, foo): self.foo = foo def execute(self): conn = Connection() result = conn.execute() return result
Tests / test _file.py
import unittest from unittest.mock import patch, MagicMock from project.file import FileRemoveOp class TestFileRemoveOp(unittest.TestCase): def setUp(self): self.fileremoveop = FileRemoveOp('foobar') @patch('project.file.Connection') def test_execute(self, connection_mock):
source share