Wil*_*uck 19 python testing unit-testing mocking python-unittest
为了避免循环导入,我被迫定义一个看起来像这样的函数:
# do_something.py
def do_it():
from .helpers import do_it_helper
# do stuff
Run Code Online (Sandbox Code Playgroud)
现在我希望能够通过do_it_helper
修补来测试这个功能.如果导入是顶级导入,
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('do_something.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
Run Code Online (Sandbox Code Playgroud)
会工作得很好.但是,上面的代码给了我:
AttributeError: <module 'do_something'> does not have the attribute 'do_it_helper'
Run Code Online (Sandbox Code Playgroud)
一时兴起,我也尝试将补丁语句更改为:
with patch('do_something.do_it.do_it_helper') as helper_mock:
Run Code Online (Sandbox Code Playgroud)
但这产生了类似的错误.有没有办法模拟这个函数,因为我被迫在它使用的函数中导入它?
ale*_*cxe 34
你应该嘲笑helpers.do_it_helper
:
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('helpers.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
Run Code Online (Sandbox Code Playgroud)
这是一个使用mock on的例子os.getcwd()
:
import unittest
from mock import patch
def get_cwd():
from os import getcwd
return getcwd()
class MyTestCase(unittest.TestCase):
@patch('os.getcwd')
def test_mocked(self, mock_function):
mock_function.return_value = 'test'
self.assertEqual(get_cwd(), 'test')
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.