Mocking __init__() for unittesting
mocking, python, sqlite, unit-testing
Solution
Instead of mocking, you could simply subclass the database class and test against that:
class TestingDatabaseThing(DatabaseThing):
def __init__(self, connection):
self.connection = 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.
Problem
I have a class: ``` 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);''') ``` 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.