How TDD can be applied to Django Class based Generic Views?

前端 未结 3 1790
误落风尘
误落风尘 2021-02-02 10:13

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

3条回答
  •  孤城傲影
    2021-02-02 10:54

    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.

提交回复
热议问题