You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django测试中用Selenium访问数据库验证表单提交结果?

解决方法

你完全可以在测试方法里直接通过Django的ORM访问测试数据库,核心是用LiveServerTestCase配合Selenium,两者共享同一个测试数据库,具体步骤如下:

1. 使用LiveServerTestCase替代普通TestCase

普通TestCase不会启动真实服务器,无法让Selenium访问;而LiveServerTestCase会自动启动一个临时测试服务器,并且自动创建隔离的测试SQLite数据库,Selenium操作的就是这个数据库,测试代码也能直接通过ORM访问它。

2. 编写测试代码示例

from django.test import LiveServerTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.webdriver import WebDriver
from your_app.models import Title  # 替换成你的app名称

class TitleSubmissionTest(LiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # 初始化Selenium驱动(这里用Firefox,你可以换成Chrome等)
        cls.selenium = WebDriver()
        cls.selenium.implicitly_wait(10)  # 设置隐式等待

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()  # 关闭浏览器
        super().tearDownClass()

    def test_title_submission(self):
        # 访问测试服务器的表单页面
        self.selenium.get(f"{self.live_server_url}/your-form-path/")  # 替换成你的表单URL

        # 模拟输入标题
        test_title_content = "测试标题示例"
        title_input = self.selenium.find_element(By.NAME, "title")
        title_input.send_keys(test_title_content)

        # 点击提交按钮
        submit_btn = self.selenium.find_element(By.ID, "submit-button")  # 替换成你的按钮ID/选择器
        submit_btn.click()

        # 直接用ORM查询测试数据库中的数据
        # 验证提交的数据是否存在
        submitted_title = Title.objects.get(title=test_title_content)
        self.assertEqual(submitted_title.title, test_title_content)

关键注意事项

  • 不要手动运行./manage.py runserver:LiveServerTestCase会自动启动临时服务器,手动启动的开发服务器使用的是开发数据库,和测试数据库不共享,无法在测试代码中查询到数据。
  • 数据库隔离:测试结束后,LiveServerTestCase会自动销毁测试数据库,不会污染你的开发数据。
  • 关于主键:你手动设置了id = models.IntegerField(primary_key=True),要确保表单提交时正确处理id值,或者可以去掉这个字段,让Django自动生成自增主键,避免出现主键重复的错误。

内容的提问来源于stack exchange,提问作者agctute

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:45:38