我正在尝试模拟fetchall()
fromdbconnection
光标对象。我正在尝试使用预期返回值的以下代码。但是,它没有返回值。我现在有了答案并编辑了单元测试以包含答案 db.py
def query_db(db_connection, query):
"""
:param db_connection: dbconnection object
:param query: query to be executed
:return:
"""
cur = db_connection.cursor()
try:
logging.info(f"Query to be executed : {query}")
cur.execute(query)
results = cur.fetchall()
logging.info(f"Query Results : {results}")
except Exception:
logging.exception("Exception while executing \'query_db\' function")
raise Exception(f"Error while executing query : {query}. Please check the logs for details")
return results
测试用例:
def test_get_client_object(self):
dbconnection = Mock(name="dbconnection")
mycursor = Mock(name="mycursor")
mycursor.fetchall.return_value = "testing_return_value"
dbconnection.cursor.return_value = mycursor # I was doing dbconnection.cursor = mycursor . ... which caused the error
self.assertEqual("testing_return_value", utils.query_db(dbconnection, 12345))
我得到了以下断言错误。它返回一个模拟对象而不是预期的返回值。
<Mock name='mycursor().fetchall()' id='4443879760'> != testing_return_value
Expected :testing_return_value
Actual :<Mock name='mycursor().fetchall()' id='4443879760'>
<Click to see difference>