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

前端 未结 3 1250
深忆病人
深忆病人 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条回答
  •  难免孤独
    2021-02-07 13:16

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

提交回复
热议问题