首页 > 解决方案 > 如何在 django 单元测试中模拟装饰器?

问题描述

我正在尝试为我的观点编写简单的单元测试。我有一个装饰器,它通过发送 http 请求进行身份验证。如何模拟我的视图装饰器并运行单元测试?

我的意见.py

@method_decorator(authentication_decorator, name='post')
class AddBlogView(CreateAPIView):
    serializer_class = BlogSerializer

标签: pythondjangounit-testingdjango-rest-frameworkmocking

解决方案


试试这个(为您的应用程序和文件名调整代码):

from mock import patch
patch('app.decorators.authentication_decorator', lambda x: x).start()  # This line must come before other imports

from app.views import AddBlogView
# Test AddBlogView

推荐阅读