【问题标题】:How to skip method call in the DRF unit-test?如何在 DRF 单元测试中跳过方法调用?
【发布时间】:2017-11-27 19:08:51
【问题描述】:

我不清楚如何正确使用unittest.mock。我需要使用rest_framework.test.APITestCase.client 测试APIView。但我不需要调用其中一种方法。

class MyClass(MyMixin):
    def do_some_stuff(self, request):
        self.should_be_called_in_the_test()
        self.should_not_be_called_in_the_test()

class MyView(views.APIView):
    def post(self, request):
        my_object = MyClass()
        my_object.do_some_stuff(request)
        return Response(status=status.HTTP_200_OK)

#test.py:
class MyViewTest(APITestCase):
    def test_post_request(self):
        url = reverse('my-view-url')
        # How properly skip call of "should_not_be_called_in_the_test()" ?
        response = self.client.post(url, data)
        # some asserts...

【问题讨论】:

    标签: python unit-testing mocking django-rest-framework


    【解决方案1】:

    您需要使用patch 而不是模拟。你可以用这样的东西来做,

    #views.py
    class MyClass(MyMixin):
        def do_some_stuff(self, request):
            self.should_be_called_in_the_test()
            self.should_not_be_called_in_the_test()
    
    class MyView(views.APIView):
        def post(self, request):
            my_object = MyClass()
            my_object.do_some_stuff(request)
            return Response(status=status.HTTP_200_OK)
    
    #test.py:
    class MyViewTest(APITestCase):
        def test_post_request(self):
            url = reverse('my-view-url')
            with patch('app.views.MyClass.should_not_be_called_in_the_test'):
                response = self.client.post(url, data)
            # some asserts...
    

    使用补丁时,您通常必须小心在哪里打补丁,这在here 中进行了解释

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-31
      • 2018-10-23
      • 2013-07-05
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多