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

查看:57
本文介绍了模拟 __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__() 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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