26π
β
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
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()
π€Sebastian Wozny
16π
Update β available in Django 3.0
As stated in Sebastianβs answer he got the code snippet from django-downloadview docs. In there they state:
This is an early implementation of https://code.djangoproject.com/ticket/20456
A few years later, this feature is now part of Django, as you can read in the docs, so you would just need to do:
from django.test import RequestFactory, TestCase
from .views import MyClassBasedView
class MyClassBasedViewTest(TestCase):
def test_my_method(self):
request = RequestFactory().get('/')
view = MyClassBasedView()
view.setup(request)
view.my_method()
The view.setup()
method is precisely what was suggested in the accepted answer, but I think it is better to use the one from Django π
π€NBajanca
- How can I make a fixture out of QuerySet in django?
- Django: WSGIRequest' object has no attribute 'user' on some pages?
- What is the right way to use angular2 http requests with Django CSRF protection?
- How can I schedule a Task to execute at a specific time using celery?
- Converting a django ValuesQuerySet to a json object
- Changing password in Django Admin
Source:stackexchange.com