Easier unit testing for class-based views
|Reported by:||benoitbryon||Owned by:||auvipy|
|Cc:||bmispelon@…, marc.tamlyn@…, Natim, unai@…||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
When django users create class-based views, they create custom code. Testing this code matters. Writing unit tests for the custom code (and only for the custom code) is important.
As of Django 1.5, the easiest way to test class-based views is using the builtin test client. But it performs integration tests, i.e. involves middlewares, URL resolvers, decorators...
It is also quite easy to use django.test.RequestFactory and as_view() classmethod. But, since as_view() returns a function, the tests can only check the response. It means the class-based views are tested as a system.
It seems that writing unit tests is possible, i.e. we can write unit tests for class-based views methods.
There is at least one technique which was presented at DjangoCon Europe 2013 Warsaw:
The recipe mentioned above seems to work (to be confirmed). But wouldn't be better if the recipe was documented in Django's documentation (https://docs.djangoproject.com/en/1.5/topics/testing/advanced/ I guess) and tools (setup_view) were builtin Django?
Note: perhaps, it would be even better if setup_view() is not a standalone function but is a method of View class. Something like as_view(), but which returns an instance.
Change History (11)
comment:1 Changed 3 years ago by bmispelon
- Cc bmispelon@… added
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 3 years ago by mjtamlyn
- Cc marc.tamlyn@… added
- Keywords cbv test added
- Owner changed from nobody to mjtamlyn
- Status changed from new to assigned
- Triage Stage changed from Unreviewed to Accepted