我想使用psycopg2测试我的数据库类,但是我遇到了问题-我不知道如何测试close()方法。我已经尝试了一些想法,但这是下面的最后一个,它没有用。有人知道怎么嘲笑吗?
db.py
import psycopg2
class DB:
def __init__(self, name: str) -> None:
self.name = name
self.conn = psycopg2.connect(dbname=self.name,
host="localhost",
port="5432",
user="postgres",
password="postgres")
def disconnect(self):
self.conn.close()
test_db.py
import unittest
from unittest import mock
import psycopg2
from db import DB
class TestDB(unittest.TestCase):
def setUp(self) -> None:
self.db = DB("testdb")
def tearDown(self) -> None:
self.db.disconnect()
@mock.patch("db.psycopg2.connect")
def test_DB_should_connect_to_db(self, mock_connect):
DB("testdb")
mock_connect.assert_called_with(dbname="testdb",
host="localhost",
port="5432",
user="postgres",
password="postgres")
@mock.patch("db.psycopg2.connect")
def test_db_should_disconnect_from_db(self, mock_connect):
mock_conn = mock_connect.return_value
mock_close = mock_conn.close
self.db.disconnect()
mock_close.assert_called_once()
if __name__ == '__main__':
unittest.main()