python—如何使测试成为一个在其_uinit中创建了到数据库的连接的类?

e37o9pze  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(362)

我有一个类,它创建了一个到db的连接(执行时需要处于活动状态),我想对该类的方法(不使用连接)进行单元测试。如何模拟或忽略与数据库的连接?

from myutils import MyConnect
class Module:
    def __init__(self, payload):
        self.payload = payload
        format_date = "%Y-%m-%d"
        days = self.payload["days"]
        self.start_date = (datetime.now() - timedelta(days=days)).strftime(format_date)
        self.end_date = datetime.now().strftime(format_date)
        self.domain = self.payload["domain"]

        self.ms_connection = MyConnect(self.payload["MYSQL"]) # create connection to db
ha5z0ras

ha5z0ras1#

而不是硬编码 MyConnect ,将用于创建连接的类添加为参数(其默认值可以硬编码为 MyConnect :

class Module:
    def __init__(self, payload, connecton_cls=MyConnect):
        self.payload = payload
        format_date = "%Y-%m-%d"
        days = self.payload["days"]
        self.start_date = (datetime.now() - timedelta(days=days)).strftime(format_date)
        self.end_date = datetime.now().strftime(format_date)
        self.domain = self.payload["domain"]

        self.ms_connection = connection_cls(self.payload["MYSQL"])

为了测试该方法,您可以传递创建模拟连接所需的任何调用。

def test_thing():
    m = Module(some_payload, Mock)
8yparm6h

8yparm6h2#

如果要测试此类的某些函数,可以使用mocker并修补对象。

myconnect = mocker.MagicMock(spec=MyConnect)

# Patch MyConnect so this will return mocker object of MyConnect class

mocker.patch.object(mut, "MyConnect", return_value=myconnect) # module under test(mut

相关问题