【发布时间】:2015-08-02 12:17:16
【问题描述】:
我想为我的 Django 应用程序添加测试。在阅读了几篇关于单元测试与集成测试的帖子(尤其是this SO posting)后,我不确定以下情况:
单元测试是告诉您错误到底在哪里的唯一测试。要获取此信息,他们必须在模拟环境中运行该方法,所有其他依赖项都应该正常工作。
在测试我的表单时(实际上是 ModelForms),我依赖 Django 的 feature to provide test-data by a fixture。因此,我的表单测试使用 normal Django 方法,例如 Foo.objects.get()。
但是,上面链接的 SO 帖子建议在不依赖外部组件的情况下执行单元测试。那么我应该放弃单元测试的固定装置并仅在集成测试中使用它们吗?
这是我当前的表单测试设置示例:
from django.test import TestCase
class FooTest(TestCase):
"""Base class for all app related tests"""
fixtures = ['testdata.json']
class BarFormTest(FooTest):
"""Tests for the BarForm"""
def test_constructor(self):
"""Tests if the form stores the supplied user"""
# this is the line I'm unsure of:
u = User.objects.get(username='TestUser01')
# is this better?
# u = User(username='TestUser01')
form = BarForm(data=None, user=u)
self.assertEqual(u, form.user)
不要误会我的意思,我的测试按预期工作。我只是不确定我是否可以依赖外部(Django 内置)函数。它们也经过测试,因此我的测试中的任何错误很可能源自 my 代码。
我应该为集成测试留出固定装置吗?我希望这个问题不是太宽泛,我在这里询问 Django 最佳实践。
【问题讨论】:
标签: python django unit-testing integration-testing django-testing