如何在django基于类的视图中对测试方法进行单元化? [英] How to unit test methods inside django's class based views?
问题描述
我需要在django基于类的视图中测试方法和辅助函数。
I need to test the methods and helper function inside a django Class Based View.
请考虑以下基于类的视图:
Consider this Class Based View:
class MyClassBasedView(View):
def dispatch(self, request, *args, **kwargs):
....
def __get_render_dict():
d = {}
...
return d
def my_method(self):
render_dict = self.__get_render_dict()
return render_response(self.request, 'template.html', render_dict)
为了为我的视图编写单元测试,我需要调用内部的方法,直接说 __ get_render_dict()
。我该如何实现??
In order to write unit tests for my view, I need to call the methods inside, say __get_render_dict()
directly. How can I achieve this?.
我尝试过
v = MyClassedBasedView()
v.dispatch(request,args, kwargs)
v.__method_name()
但这失败了,因为post / get方法中的参数不匹配,即使我在不使用URL的情况下调用方法不透明。
but this fails with not matching parameters in post/get method, even though I was calling the method direclty without using URL.
推荐答案
要在单元测试中使用基于类的视图,请尝试从
To use class based views in your unittests try setup_view
from here.
def setup_view(view, request, *args, **kwargs):
"""
Mimic ``as_view()``, but returns view instance.
Use this function to get view instances on which you can run unit tests,
by testing specific methods.
"""
view.request = request
view.args = args
view.kwargs = kwargs
return view
您仍然需要向其提供请求,可以使用 django.test.RequestFactory
:
You still need to feed it a request, you can do this with django.test.RequestFactory
:
factory = RequestFactory()
request = factory.get('/customer/details')
然后可以对您的方法进行单元测试:
You can then unittest your methods:
v = setup_view(MyClassedBasedView(), request)
v.method_name()
这篇关于如何在django基于类的视图中对测试方法进行单元化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!