Python 如何在DRF单元测试中跳过方法调用?
我不清楚如何正确使用Python 如何在DRF单元测试中跳过方法调用?,python,unit-testing,mocking,django-rest-framework,Python,Unit Testing,Mocking,Django Rest Framework,我不清楚如何正确使用unittest.mock。我需要使用rest\u 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() cl
unittest.mock
。我需要使用rest\u 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...
您将需要使用而不是模拟。你可以这样做
#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...
当使用补丁时,你通常必须小心补丁的位置,这是解释的