How to mock a non instance method in python?

  python, unit-testing

I have a test case where I have to mock a non instance method, when I mock an instance method it working fine but the same if I try for a non instance method I am not able to mock it. The method gets executed.

Instance method (woking fine) :

common.send_email

class Email:
    def send_mail(self):
        print("sending email")


def send_mail_2():
    print("sending mail 2")

common.test_mocking

import unittest
from unittest.mock import patch
from common.send_mail import Email, send_mail_2

class Test(unittest.TestCase):
    @patch('common.send_mail.send_mail_2')
    @patch('common.send_mail.Email.send_mail')
    def test_send_email(self, mock_instance, mock_non_instance):
        mock_instance.return_value = 1
        mock_non_instance.return_value = 1
        res = Email().send_mail()
        assert res == 1
        res1 = send_mail_2()
        assert res1 == 1

Here, mocking the send_mail works but mocking send_mail_2 failing.
how can we mock send_mail_2() method?

Source: Python Questions

LEAVE A COMMENT