如何对 Django 模型进行单元测试?
How to unittest a Django modelform?
我想为我的 Django 应用程序添加测试。在阅读了几篇关于单元测试与集成测试(尤其是 this SO posting)的帖子后,我不确定以下情况:
Unit tests are the sole tests that tell you where exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.
在测试我的表单时(实际上是 ModelForm
s),我依赖 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 代码。
我应该为集成测试保留 fixtures 吗?我希望这个问题不会 太宽泛 ,我在这里问的是 Django 最佳实践。
这取决于你想要多确定,你可以相信你的单元测试。
如果您不信任 django 的内部函数,则不应使用 django,而应在整个项目中使用纯 python。
如果您不信任 python 的内部函数,则不应使用 python,而应使用 C。
如果你不信任 C,你应该使用汇编程序。 …
django 本身包含单元测试,可确保每个版本都按预期工作。所以您可以放心 ORM 按预期工作。
我想为我的 Django 应用程序添加测试。在阅读了几篇关于单元测试与集成测试(尤其是 this SO posting)的帖子后,我不确定以下情况:
Unit tests are the sole tests that tell you where exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.
在测试我的表单时(实际上是 ModelForm
s),我依赖 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 代码。
我应该为集成测试保留 fixtures 吗?我希望这个问题不会 太宽泛 ,我在这里问的是 Django 最佳实践。
这取决于你想要多确定,你可以相信你的单元测试。
如果您不信任 django 的内部函数,则不应使用 django,而应在整个项目中使用纯 python。 如果您不信任 python 的内部函数,则不应使用 python,而应使用 C。 如果你不信任 C,你应该使用汇编程序。 …
django 本身包含单元测试,可确保每个版本都按预期工作。所以您可以放心 ORM 按预期工作。