我应该如何对 MySQL 查询进行单元测试? [英] How should I unit test MySQL queries?

查看:76
本文介绍了我应该如何对 MySQL 查询进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 Python 模块构建一些单元测试,该模块通过 SQLAlchemy 与 MySQL 数据库连接.通过阅读,我发现最好的方法是创建一个测试数据库,我可以像查询真实数据库一样进行查询.我已经这样做了,但是我应该如何测试模块中的现有查询,因为它们目前都指向实时数据库?

I'm building some unit tests for my Python module which interfaces with a MySQL database via SQLAlchemy. From reading around I gather the best way to do this is to create a test database that I can query as if it was the real thing. I've done this however how should I test the existing queries in the module as they currently all point at the live database?

我想出的唯一想法是执行以下操作:

The only idea I'd come up with was to do something like the following:

def run_query(engine, db_name='live_db')
    engine.execute(f'SELECT * FROM {db_name}.<table_name>')

然后,当我从 unittest 运行函数时,我可以传入 test_db.有没有更好的办法?

I could then pass in test_db when I run the function from unittest. Is there a better way?

推荐答案

对于可扩展的测试方法,我建议使用一个中间 DAL 层来决定应该将查询路由到哪个 DB.

For a scalable testing approach, I would suggest having an intermediate DAL Layer than should decide to which DB the query should be routed.

使用测试数据库进行测试

这篇关于我应该如何对 MySQL 查询进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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