如何解决如何在Django中编写纯单元测试?
所以我的问题是,如何用Django编写纯单元测试?
例如,我有这个模型:
class Topic(models.Model):
title = models.CharField(max_length=255,validators=[MinLengthValidator(5)])
created_at = models.DateTimeField(auto_now_add=True)
此序列化器:
class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topic
fields = ('id','title','created_at')
我写了这些测试:
class TopicModelTest(TestCase):
def test_create_topic(self):
topic = Topic(title='Topic title')
self.assertEqual(topic.title,'Topic title')
def test_too_short_title(self):
topic = Topic(title='W'*4)
with self.assertRaises(ValidationError):
topic.save()
topic.full_clean()
class TopicSerializerTest(TestCase):
def setUp(self) -> None:
mocked = datetime.datetime(2020,1,tzinfo=pytz.utc)
self.topic_attr = {'title': 'What is the weather like?'}
self.topic_serialized = {'id': 1,'title': 'What is the weather like?','created_at': '2020-01-01T00:00:00Z'}
with mock.patch('django.utils.timezone.now',mock.Mock(return_value=mocked)):
self.topic = Topic.objects.create(**self.topic_attr)
self.serializer = TopicSerializer(instance=self.topic)
def test_contains_expected_fields(self):
data = self.serializer.data
self.assertCountEqual(data.keys(),['id','created_at'])
def test_serialized_data(self):
self.assertEqual(self.serializer.data,self.topic_serialized)
一切正常,但这不是单元测试。这是集成测试,因为使用了数据库。
所以我的问题是,如何编写单元测试?我之所以这么问,是因为许多公司希望为初级用户编写带有单元测试(TDD)的简单项目,但是我不知道如何在没有DB的情况下编写独立的单元测试
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。