模拟 __init__() 进行单元测试

Mocking __init__() for unittesting(模拟 __init__() 进行单元测试)
本文介绍了模拟 __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__() 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Inserting NaN value into MySQL Database(将NaN值插入MySQL数据库)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)
in sqlite update trigger with multiple if/Case Conditions(在具有多个IF/CASE条件的SQLite UPDATE触发器中)