How to unit test methods inside django's class based views?

前端 未结 3 1291
深忆病人
深忆病人 2021-02-07 12:38

I need to test the methods and helper function inside a django Class Based View.

Consider this Class Based View:

class MyClassBasedView(View):

    def d         


        
3条回答
  •  Happy的楠姐
    2021-02-07 13:18

    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 :)

提交回复
热议问题