Mocking __init__() for unittesting(模拟 __init__() 进行单元测试)
问题描述
我有一堂课:
class DatabaseThing():
def __init__(self, dbName, user, password):
self.connection = ibm_db_dbi.connect(dbName, user, password)
我想用一个测试数据库来测试这个类.所以在我的测试课中,我正在做这样的事情:
I want to test this class but with a test database. So in my test class I am doing something like this:
import sqlite3 as lite
import unittest
from DatabaseThing import *
class DatabaseThingTestCase(unittest.TestCase):
def setUp(self):
self.connection = lite.connect(":memory:")
self.cur = self.connection.cursor()
self.cur.executescript ('''CREATE TABLE APPLE (VERSION INT, AMNT SMALLINT);
INSERT INTO APPLE VALUES(16,0);
INSERT INTO APPLE VALUES(17,5);
INSERT INTO APPLE VALUES(18,1);
INSERT INTO APPLE VALUES(19,15);
INSERT INTO APPLE VALUES(20,20);
INSERT INTO APPLE VALUES(21,25);''')
与我要测试的课程的连接相比,我将如何使用此连接?意思是使用来自 setUp(self)
的连接,而不是来自 DatabaseThing
的连接.如果不实例化类,我无法测试这些功能.我想在测试类中以某种方式模拟 __init__
方法,但我没有在 文档.
How would I go about using this connection than the connection from the class I want to test? Meaning using the connection from setUp(self)
instead of the connection from DatabaseThing
. I cannot test the functions without instantiating the class. I want to mock the __init__
method somehow in the Test Class, but I didn't find anything that seemed useful in the documentation.
推荐答案
您可以简单地继承数据库类并对其进行测试,而不是模拟:
Instead of mocking, you could simply subclass the database class and test against that:
class TestingDatabaseThing(DatabaseThing):
def __init__(self, connection):
self.connection = connection
并为您的测试实例化 that 类而不是 DatabaseThing
.方法还是一样,行为还是一样,但是现在所有使用 self.connection
的方法都使用你的测试提供的连接.
and instantiate that class instead of DatabaseThing
for your tests. The methods are still the same, the behaviour will still be the same, but now all methods using self.connection
use your test-supplied connection instead.
这篇关于模拟 __init__() 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模拟 __init__() 进行单元测试


基础教程推荐
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01