我应该如何在Django中编写针对Forms的测试? [英] How should I write tests for Forms in Django?

查看:63
本文介绍了我应该如何在Django中编写针对Forms的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写测试时,我想在Django中模拟对视图的请求。这主要是测试表格。以下是一个简单测试请求的摘要:

I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
        self.assertEqual(response.status_code, 200) # we get our page back with an error

页面始终返回响应200是否存在表格错误。如何检查我的表单是否失败以及特定字段( soemthing )是否有错误?

The page always returns a response of 200 whether there's an form error or not. How can I check that my Form failed and that the particular field (soemthing) had an error?

推荐答案

我认为,如果您只想测试表单,则应该只测试表单,而不是测试呈现表单的视图。示例示例:

I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:

from django.test import TestCase
from myapp.forms import MyForm

class MyTests(TestCase):
    def test_forms(self):
        form_data = {'something': 'something'}
        form = MyForm(data=form_data)
        self.assertTrue(form.is_valid())
        ... # other tests relating forms, for example checking the form data

这篇关于我应该如何在Django中编写针对Forms的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆