class CanonDatabase:
def __init__(self, clean_up_db=False):
self.db = "tmg_canon_april_tokens"
self.conn = create_connection(self.db)
self.cur = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)为了传递构造函数,我尝试使用mock.patch MySQLdb。
@mock.patch.object(MySQLdb, '__init__')
class TestDatabase(unittest.TestCase):
def setUp(self):
super(TestDatabase, self).setUp()
patch = mock.patch('atone_canon.Database.create_connection')
mock_baz = patch.start()
mock_baz.cursor.return_value = mock.MagicMock()
def tearDown(self):
super(TestDatabase, self).tearDown()
mock.patch.stopall()
def test_clean_table(self, mysql_mock):
db = CanonDatabase()
self.assertEqual(True, False)但是,如果出现以下错误消息,则会失败:
文件"atone_canon/Database.py",第20行,在self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) = __init__ self.cur中 AttributeError:“模块”对象没有属性“游标”
我找到了一个方法:
如果我在单元测试中插入此导入,则不包含(!)即使使用它:
from MySQLdb.cursors import DictCursor这样我就不再得到错误了,我甚至不需要mock.patch MySQLdb包装器了:
# @mock.patch.object(MySQLdb, '__init__')
class TestDatabase(unittest.TestCase):
...对解决方案不太满意。通常,我很难模拟项目之外的类(例如,生活在虚拟环境中)。我把这个打开,希望有人能教我如何模拟这类类。
发布于 2015-02-09 22:43:46
首先:确保在Database.py中有
import MySQLdb.cursors否则,即使您没有修补任何内容,也会引发上述错误。如果需要重复检查,请将cur=MySQLdb.cursors.DictCursor添加到__init__顶部并删除所有修补程序:您将在新行中发现相同的错误。如果在尝试指向MySQLdb.cursors之前在上下文中的某个位置加载MySQLdb.cursors.DictCursor,该错误将消失。如果您想知道以前没有看到这个错误,是因为在您的生产代码中您在使用MySQLdb.cursors之前导入了CanonDatabase()
现在,进行一个构造函数将通过的测试,create_connection邪恶函数--不要试图连接任何东西--只需修补create_connection和其他任何东西即可获得:
class TestSimpler(unittest.TestCase):
@mock.patch('atone_canon.Database.create_connection')
def test_base(self, mock_create_connection):
db = CanonDatabase()
self.assertIsNotNone(db)当然,如果您希望为每个测试方法安装补丁create_connection,您可以装饰测试类。
https://stackoverflow.com/questions/28345645
复制相似问题