有谁知道我应该如何为这个表单编写单元测试:
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(
choices=PRODUCT_QUANTITY_CHOICES,
coerce=int)
update = forms.BooleanField(required=False,
initial=False,
widget=forms.HiddenInput)
答案 0 :(得分:3)
from django.test import TestCase
from myapp.forms import CartAddProductForm
class MyTests(TestCase):
def test_form(self):
form_data = {'quantity':100, 'update':True}
form = CartAddProductForm(data=form_data)
self.AssertTrue(form.is_valid())
def test_form_without_update(self):
form_data = {'quantity':100}
form = CartAddProductForm(data=form_data)
self.AssertTrue(form.is_valid())
def test_form_is_invalid(self):
form_data = {'quantity':'foo', 'update':'bar'}
form = CartAddProductForm(data=form_data)
self.AssertFalse(form.is_valid())
有很多测试方法,你可以在一个表单中测试,它依赖于你试图测试的描述性测试。
我发现这篇关于测试用例的好文章:http://test-driven-django-development.readthedocs.io/en/latest/05-forms.html