I have one class (Cat) and one method (say_hello) to patch. When I patch the class only, everything works well. When I patch the method only, it works too. When I patch both at the same time, the class is not patched but the method is properly patched.
main.py
from hello import say_hello
from cat import Cat
cat = Cat('kitty')
def main():
print(say_hello())
hello.py
def say_hello():
return "No mocked"
test.py
import unittest
from unittest.mock import patch
class TestStringMethods(unittest.TestCase):
# cat.Cat is not patched correctly if both patch statements are there
@patch('cat.Cat')
@patch('main.say_hello')
def test_kitty(self, say_hello_mock, cat_mock):
say_hello_mock.return_value = "Mocked"
from main import main
main()
if __name__ == '__main__':
unittest.main()
If you run the previous example, a real Cat is created. If you comment the patch of main.say_hello, a mock Cat is created.
I don't know why the patch decorator is not working, but you can use this solution:
def test_kitty(self):
with patch('cat.Cat') as cat_mock:
with patch('main.say_hello') as hello_mock:
from main import main
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With