模拟__init __()进行单元测试 [英] Mocking __init__() for unittesting

查看:190
本文介绍了模拟__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 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

并实例化该类 而不是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 __()进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆