Since Class based Generic Views in Django involve some work by the framework I find very hard to work with them in a TDD style. Now I use the TestClient to access the view from the http mocked stack, but I would prefer to properly unittest specific methods (es. overrides of get_object and get_queryset ) before 'functional' testing with the TestClient.
Is there a ( quick ) way to obtain a proper instance of a ClassView to perform unit test on it?
Django's generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code.
A view is a callable which takes a request and returns a response. This can be more than just a function, and Django provides an example of some classes which can be used as views. These allow you to structure your views and reuse code by harnessing inheritance and mixins.
You need to apply the decorator to the dispatch method of the class based view. This can be done as follows: class ProfileView(View): @youdecorator def dispatch(self,request,*args,**kwargs): return super(ProfileView,self). dispatch(request,*args,**kwargs) //Rest of your code.
Class based views are excellent if you want to implement a fully functional CRUD operations in your Django application, and the same will take little time & effort to implement using function based views.
Generally, that would include creating a request via the RequestFactory
and instantiating the view class with keyword arguments. Afterwards, you can call any of the view methods and evaluate the result, passing any required arguments.
I'd recommend that you review the base View
class, specifically the __init__
, as_view
and dispatch
methods. They're crucial to understanding how the framework interacts with view objects.
The most important bit to notice there is that view methods expect to be called during a request-response process, so they're allowed to rely upon self.request
, self.args
and self.kwargs
to be present before they're called, so make sure you've got that covered.
Not sure if this is exactly what you're looking for, but this is an example of how I try to unit test my views (untested code below):
import unittest from django.core.urlresolvers import reverse from django.test.client import RequestFactory from ..views import MyClassBasedView class MyClassBasedViewTestCase(unittest.TestCase): def setUp(self): self.factory = RequestFactory() def test_list_view(self): request = self.factory.get(reverse('your_url')) # additional params can go after request response = MyClassBasedView.as_view()(request) self.assertEqual(response.status_code, 200)
I'd also recommend looking at the documentation that Filip mentioned in his answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With