user3062842
user3062842

Reputation: 53

mock a method located in the __init__.py

I would like to mock a method which is in the init.py, but actually it is not working.

There is an example to demonstrate the issue and how I tried to write the unit test:

The code under test: src.main.myfile:

from src.main.utils import a_plus_b

def method_under_test():
    a_plus_b()

The a_plus_b is in the __init__.py in the src.main.utils module:

def a_plus_b():
    print("a + b")

The unittest:

import src.main.utils
import unittest
from mock import patch
from src.main.myfile import method_under_test

class my_Test(unittest.TestCase):
    def a_plus_b_side_effect():
       print("a_plus_b_side_effect")

    @patch.object(utils, 'a_plus_b')
    def test(self, mock_a_plus_b):
        mock_a_plus_b.side_effect = self.a_plus_b_side_effect
        method_under_test()

The unit test prints the "a + b", and not the side effect. Could anyone help me out what I did wrong?

Upvotes: 5

Views: 4316

Answers (1)

chepner
chepner

Reputation: 530990

The name you need to patch isn't src.main.utils.a_plus_b, but src.main.myfile.a_plus_b, since that is what method_under_test uses.

@patch('src.main.myfile.a_plus_b')
def test(self, mock_a_plus_b):
    mock_a_plus_b.side_effect = self.a_plus_b_side_effect
    method_under_test()

Upvotes: 3

Related Questions