如何mock cursor.execute 实现无需接入MySQL的SQL查询函数单元测试
问题解答
完全可以实现无需连接真实MySQL即可完成该函数的测试,你遇到的报错是测试代码的配置错误导致的,核心问题有3个:
@mock.patch装饰器的参数注入顺序错误:装饰器的注入顺序是从下到上,你写的两个patch参数顺序写反了- 你给
database_connection的返回值设置为字符串"cursor",字符串没有execute方法,自然会触发属性报错 - 不需要单独patch
pymysql.cursors.Cursor.execute,直接构造模拟游标对象即可,逻辑更简单
修正后的测试代码示例
import unittest from unittest import mock import lambda_function # 导入你的被测函数所在模块 class TestSQLQuery(unittest.TestCase): @mock.patch("lambda_function.database_connection") def test_sql_query_select_has_result(self, mock_db_conn): # 构造模拟游标对象,自动支持execute、fetchone、close等方法的模拟 mock_cursor = mock.MagicMock() # 模拟查询到数据的场景:fetchone返回长度至少为1的序列 mock_cursor.fetchone.return_value = ["expected_result"] # 让database_connection返回我们构造的模拟游标 mock_db_conn.return_value = mock_cursor # 调用被测函数 result = lambda_function.sql_query_select("col", "test_table", "id", "1001") # 断言验证逻辑 # 验证数据库连接方法调用正确 mock_db_conn.assert_called_once_with("cursor") # 验证生成的SQL语句符合预期 mock_cursor.execute.assert_called_once_with("SELECT col from test_table where id = '1001'") # 验证游标正常关闭 mock_cursor.close.assert_called_once() # 验证返回结果正确 self.assertEqual(result, "expected_result") @mock.patch("lambda_function.database_connection") def test_sql_query_select_no_result(self, mock_db_conn): # 模拟查询无数据的场景 mock_cursor = mock.MagicMock() mock_cursor.fetchone.return_value = None mock_db_conn.return_value = mock_cursor result = lambda_function.sql_query_select("col", "test_table", "id", "9999") self.assertEqual(result, None) if __name__ == '__main__': unittest.main()
以上代码即可完成所有场景的测试,全程不需要连接真实的MySQL数据库。
内容的提问来源于stack exchange,提问作者L44TXF
相关产品推荐
相关产品推荐

