模拟位于 __init__.py 中的方法
mock a method located in the __init__.py
我想模拟 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()
我想模拟 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()