简体   繁体   English

如何为django-rest-framework api编写单元测试?

[英]How to write unit tests for django-rest-framework api's?

I have exposed my database model using Django-rest-framework view sets and routers, and I am trying to write the unit tests for it. 我使用Django-rest-framework视图集和路由器公开了我的数据库模型,我正在尝试为它编写单元测试。

Here are my API and test code 这是我的API和测试代码

Viewsets.py Viewsets.py

class Model1ViewSet(viewsets.ReadOnlyModelViewSet):

    model = Model1
    serializer_class = Model1Serializer
    filter_class = Model1Filter
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)
    ordering = ('id', 'cl1')

Serializer.py Serializer.py

class Model1Serializer(serializers.HyperlinkedModelSerializer):
    chip = serializers.HyperlinkedRelatedField(view_name="some-detail")

    class Meta:
        model = Model1
        fields = ('url', 'id', 'cl1', 'cl2', 'cl3', 'cl4')
        depth = 1

Unit-tests 单元测试

from rest_framework.test import APIClient

class TestModel1Api(unittest.TestCase):

    def setUp(self):
        self.client = APIClient()

    def test_Model1_list(self):
        response = self.client.get(reverse('Model1-list'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_Model1_detail(self):
        mm_objs = Model1.objects.all()
        if mm_objs:
            response = self.client.get(reverse('Model1-detail', args=[mm_objs[0].id]))
            self.assertEqual(response.status_code, status.HTTP_200_OK)

I don't want to connect to the database for unit testing because it falls under integration tests. 我不想连接到数据库进行单元测试,因为它属于集成测试。

Is there any way to mock the database? 有没有办法模拟数据库? I know how to apply mocking for standard view functions but here mocking is not working. 我知道如何对标准视图函数应用模拟,但这里模拟不起作用。

  1. How to write the unit tests for my REST-API? 如何为我的REST-API编写单元测试?
  2. How to mock the database in my unit-tests? 如何在我的单元测试中模拟数据库?

When you run manage.py test then the base of your database will be created but it contains no data. 运行manage.py test ,将创建数据库的基础,但它不包含任何数据。 To do that you can simply create the necessary objects yourself or use something like FactoryBoy 要做到这一点,您可以自己创建必要的对象或使用FactoryBoy之类的东西

Just keep in mind that the database is cleaned of data from previous test methods when starting a new one. 请记住,在开始新数据时,数据库会清除以前测试方法中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM