来自Intermediate-Usage Flask-RESTful 0.3.7 documentation 在底部的将构造函数参数传递到资源部分中,您将如何编写测试以模拟kwarg?旁注:我对其进行了调整,以便直接传递Smart Engine类,而不是将其实例化为变量然后传递。
from flask_restful import Resource
class TodoNext(Resource):
def __init__(self, **kwargs):
# smart_engine is a black box dependency
self.smart_engine = kwargs['smart_engine']
def get(self):
return self.smart_engine.next_todo()
您可以像这样将所需的依赖项注入TodoNext:
api.add_resource(TodoNext, '/next',
resource_class_kwargs={ 'smart_engine': SmartEngine() })
正在测试的课程:
import unittest
class TestTodoNext(unittest.TestCase):
todo_next_instance = TodoNext() # How would you mock smart_engine in this case?
答案 0 :(得分:1)
您可以使用Mock
中的unittest.mock
对象来模拟smart_engine。
import unittest
from unittest.mock import Mock
class TestTodoNext(unittest.TestCase):
smart_engine = Mock()
smart_engine.next_todo.return_value = "YOUR DESIRED RETURN VALUE"
todo_next_instance = TodoNext(smart_engine=smart_engine)
self.assertEqual(todo_next_instace.get(), "YOUR DESIRED RETURN VALUE")