我已经浏览了很多 Django 测试教程,但我有点不确定要测试多少。我主要使用基于分类的 View
例如,在测试我的 浏览次数 ,我是否应该检查以下所有内容:
我的大部分 View 都是基于类的 View 。我有一个 ListView,我在其中设置了 template_name、model 和 context_object_name。我应该测试这些设置是否正确?那里没有逻辑,因此测试它似乎有点愚蠢,因为它只是配置。
测试中 型号 :
测试中 表格 (尤其是模型表格)
很多这些测试似乎我只是在测试配置而不是逻辑。我知道如何测试上面提到的所有项目,但是当使用基于类的 View 时,如果我尝试测试所有内容,测试代码可能是实际代码量的 10 倍。
因此,我目前的想法是仅测试我的应用程序中添加逻辑的位置,而不是仅测试配置的位置。因此,如果我在模型表单或 View 中覆盖一个方法,我将对其进行测试。这听起来像是一个好方法还是我真的应该像上面提到的那样测试每一件小事?
最佳答案
我建议您从功能测试开始。它们用于自下而上测试您的整个堆栈。例如,您有一个模型、一个表单和一个创建 View 。因此,您可以进行一个测试,以确保用户可以打开创建表单,并提交该表单会导致创建对象。就像用户所做的那样:
class CreationTestCase(TestCase):
def test_creation_page_get(self):
url = reverse('your_model_create')
response = self.client.get(url)
# Your page gave 200, so there are no severe configuration errors
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'your/template.html')
# The template context contains your form, so most probably you view did fine.
self.assertEqual(type(response.context['form']), YourForm)
def test_creation_page_post(self):
payload = {'field1': 1, 'field2': 2}
response = self.client.post(reverse('your_model_create'), payload)
# Your page redirected to a success url, so the view did ok.
self.assertRedirects(response, reverse('your-success-url'))
# The instance is actually created and contains the right data
instance = YourModel.objects.first()
self.assertEqual(instance.field1, payload['field1'])
在这里,我们通过模拟用户行为测试了您的 urlconf、 View 、表单和模型。此外,您可以自由更改基础 View 和表单,保持相同的用户工作流程。
功能测试的最大缺点是速度。当您测试整个应用程序时,您的测试用例可能需要很多时间。
就我个人而言,当我看到要重构的代码中的逻辑块时,我倾向于编写单元测试,或者它似乎值得测试。
换句话说,测试行为,而不是配置。
关于django - Django 中的单元测试 - 在哪里划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155811/