我是使用新的自定義用戶模型在django 1.5b中測試註冊表單的單元。我想測試我的自定義clean_email方法提出了在新用戶試圖用已有的電子郵件註冊一個ValidationError,這裏是乾淨的方法,我寫道:`Django:單元測試表單和KeyError
def clean_email(self):
email = self.cleaned_data["email"]
try:
user = MyUser.objects.get(email=email)
raise forms.ValidationError("This email address already exists.")
except MyUser.DoesNotExist:
return email
測試代碼:
def test_clean_email(self):
data = {'email': '[email protected]'}
form = MyForm(data)
actual = form.errors['email']
expected = [u'This email address already exists.']
self.assertEqual(actual, expected)
我得到這個運行測試後:
actual = form.errors['email']
KeyError: 'email'
你的MyForm有一個名爲email的字段嗎? – iMom0