模拟位于__init__.py中的方法

问题描述 投票:1回答:1

我想模拟一个在init.py中的方法,但实际上它不起作用。

有一个例子来演示这个问题以及我如何编写单元测试:

测试中的代码:src.main.myfile:

from src.main.utils import a_plus_b

def method_under_test():
    a_plus_b()

a_plus_b位于src.main.utils模块的__init__.py中:

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

单位测试:

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()

单元测试打印“a + b”,而不是副作用。任何人都可以帮我解决我做错的事吗?

python unit-testing python-unittest python-mock
1个回答
1
投票

你需要补丁的名称不是src.main.utils.a_plus_b,而是src.main.myfile.a_plus_b,因为这是method_under_test使用的名称。

@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()
© www.soinside.com 2019 - 2024. All rights reserved.