我有一个实用函数,它接受参数大小写并相应地返回值
helper.py
def get_sport_associated_value(dictionary, category, case):
if case == 'type':
return "soccer"
else:
return 1 #if case = 'id'
我有一个使用上述功能的主要功能
crud_operations.py
def get_data(category):
dictionary ={.....}
id = get_sport_associated_value(dictionary, category, 'id')
.....
.....
type = get_sport_associated_value(dictionary, category, 'type')
....
return "successful"
现在我正在使用 unittest.Mock 对get_data()模块进行单元测试。我无法将值传递给id 和 type。
@mock.patch('helper.get_sport_associated_value')
def test_get_data(self, mock_sport):
with app.app_context():
mock_sport.side_effect = self.side_effect
mock_sport.get_sport_associated_value("id")
mock_sport.get_sport_associated_value("type")
result = get_queries("Soccer")
asserEquals(result, "successful")
def side_effect(*args, **kwargs):
if args[0] == "type":
print("Soccer")
return "Soccer"
elif args[0] == "id":
print("1")
return 1
我尝试使用side_effect函数并面临根据输入参数的不同值模拟get_sport_associated_value()的问题。
问题 2:在这种情况下使用mock或mock.magicmock的最佳方法是什么?
感谢单元测试的任何帮助谢谢