簡體   English   中英

創建數據庫以在sqlite中進行單元測試

[英]Create database for unit testing in sqlite

我有一個簡單的基於類的sqlite應用程序。 基本上,我想為此運行單元測試,但是到目前為止我還沒有能力。

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

任何類都可以使用它:

class Hello:
    def hi(self):
        db = DB() # Create db or connect to existing one
        cursor = db.connection.cursor()

現在,在測試時,我傳遞了一個測試數據庫:

db = DB('test.db')
#create datatabase here and all works fine
h = Hello()

現在,h使用mydb.db而不是test.db。 如何測試上述結構?

如果要傳遞DB類( db )的實例,則需要將該實例提供給Hello類。 嘗試:

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

class Hello:
    def hi(self, db=DB()): # we make it have a default db of DB() (which in turn defaults to 'mydb.db')
        # db = DB() # Create db or connect to existing one
        # ^^ we remove this line because now this is the default
        cursor = db.connection.cursor()

db = DB('test.db') # this makes an instance of your DB class and calls it "db"
h = Hello(db) # now we need to feed this instance

盡管這可能不是解決問題的最佳方法。 擁有一個帶有方法的類可能會從中受益更多,因為您的第二個類基本上是無用的,並且無論如何與您的第一類非常相關:

class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

    def hello(self): # making a method instead
        cursor = self.connection.cursor()

db = DB('test.db') # this makes an instance of your DB class and calls it "db"
db.hello() # call our method

編輯

我錯過了最初通過測試代碼發現的東西。 您的代碼應該可以正常工作,但是您需要調用已創建的方法! 嘗試這個:

import sqlite3

class DB:
    def __init__(self, dbname='mydb.db'):
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass

class Hello:
    def hi(self):
        db = DB('test.db')
        cursor = db.connection.cursor()

db = DB('test.db')
h = Hello() # make our instance
h.hi() # use the method "hi" associated with the class (our function name within the class)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM