根据不同的输入参数模拟Python函数unittest Python
我有一个实用函数,它接受参数大小写,并相应地返回值根据不同的输入参数模拟Python函数unittest Python,python,unit-testing,mocking,magicmock,Python,Unit Testing,Mocking,Magicmock,我有一个实用函数,它接受参数大小写,并相应地返回值 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):
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和类型时遇到问题
@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
我尝试使用副作用函数,并根据输入参数的不同值来模拟获取与运动相关的值()
问题2:在这种情况下,使用mock或mock.magicmock的最佳方法是什么
单元测试方面的任何帮助都将不胜感激
谢谢您错误地将
参数[0]
作为案例进行测试。side_effect
回调函数的参数应与要模拟的函数相同:
def side_effect(dictionary, category, case):
if case == "type":
return "Soccer"
elif case == "id":
return 1
!! 成功了。如果你能回答问题2,那会很有帮助。谢谢