数据库
首页 > 数据库> > 如何模拟数据库API?

如何模拟数据库API?

作者:互联网

连接数据库(即使它是内存数据库)也会减慢我的单元测试(目前花费了5分钟以上).

因此,我正在考虑模拟数据库api.

使用真实的数据库API,如果存在任何SQL语法错误或列名输入错误,则会引发异常.

在使用模拟对象时,我想不出任何方法来进行这种检查.

是否可以使用模拟对象来完成此操作?

解决方法:

当然!您可以使用自己的自定义函数模拟db-api函数,这些函数的行为与您想要的方式相同:

from sqlite3.dbapi2 import DatabaseError

mock_db_connection = Mock()

def mock_execute(query, params):
    if query == 'select firstname, lastname from student':
        return [('jim', 'brown')]
    elif query == 'select; firstname':
        raise DatabaseError('You have an error in your SQL syntax')

mock_db_connection.execute = mock_execute

# from this point, if you've patched out your db connection with the mock,
# you can make tests against connection.execute...

我假设您正在使用mock库.

但实际上-5分钟并不那么长.个人喜好,但我更喜欢保留这种依赖性-它可以帮助您捕获api错误.您永远不会完美地模拟出一个API,并且数据库并没有那么严重的外部依赖关系…

标签:mocking,tdd,python,database
来源: https://codeday.me/bug/20191127/2074828.html