我想测试表单验证逻辑的 is_valid 部分。在我的测试驱动程序中,我有:
test_animal = Animal(name="cat", number_paws="4")
test_animal_form = AnimalForm(instance=test_animal)
assertEqual(test_animal_form.is_valid(), True)
断言失败,但从我看来,表单中不应该有任何错误。我在表单中没有看到任何验证错误。如果加载到表单中的 test_animal 实例应该验证,这是否应该作为测试用例工作?
最佳答案
您看到验证错误的原因是 instance
data 不用于验证,您必须指定发送到表单的数据。
test_animal = Animal(name="cat", number_paws="4")
test_animal_form = AnimalForm(instance=test_animal)
assertEqual(test_animal_form.is_valid(), False) # No data has been supplied yet.
test_animal_form = AnimalForm({'name': "cat", 'number_paws': 4, }, instance=test_animal)
assertEqual(test_animal_form.is_valid(), True) # Now that you have given it data, it can validate.
关于django - 如何在 Django 的单元测试驱动程序中测试表单的验证逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201853/