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__() 进行单元测试
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
