Skip to main content
 首页 » 编程设计

python之模拟位于 __init__.py 中的方法

2024年12月31日19sxdcgaq8080

我想模拟 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”,而不是副作用。谁能帮我解决我做错了什么?

请您参考如下方法:

您需要修补的名称不是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()