问题描述
是否有可能在不设置数据库的情况下编写 django 单元测试?我想测试不需要设置数据库的业务逻辑.虽然设置数据库很快,但在某些情况下我真的不需要它.
Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn't require the db to set up. And while it is fast to setup a db, I really don't need it in some situations.
推荐答案
您可以子类化 DjangoTestSuiteRunner 并覆盖 setup_databases 和 teardown_databases 方法来传递.
You can subclass DjangoTestSuiteRunner and override setup_databases and teardown_databases methods to pass.
创建一个新的设置文件并将 TEST_RUNNER 设置为您刚刚创建的新类.然后,当您运行测试时,使用 --settings 标志指定您的新设置文件.
Create a new settings file and set TEST_RUNNER to the new class you just created. Then when you're running your test, specify your new settings file with --settings flag.
这是我所做的:
创建一个与此类似的自定义测试服运行器:
Create a custom test suit runner similar to this:
from django.test.simple import DjangoTestSuiteRunner
class NoDbTestRunner(DjangoTestSuiteRunner):
""" A test runner to test without database creation """
def setup_databases(self, **kwargs):
""" Override the database creation defined in parent class """
pass
def teardown_databases(self, old_config, **kwargs):
""" Override the database teardown defined in parent class """
pass
创建自定义设置:
from mysite.settings import *
# Test runner with no database creation
TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'
当您运行测试时,请按照以下方式运行它,并将 --settings 标志设置为您的新设置文件:
When you're running your tests, run it like the following with --settings flag set to your new settings file:
python manage.py test myapp --settings='no_db_settings'
更新:2018 年 4 月
自 Django 1.8 起,模块 django.test.simple.DjangoTestSuiteRunner
被移动到'django.test.runner.DiscoverRunner'
.
Since Django 1.8, the module django.test.simple.DjangoTestSuiteRunner
were moved to 'django.test.runner.DiscoverRunner'
.
欲了解更多信息,请查看官方文档 关于自定义测试运行器的部分.
For more info check official doc section about custom test runners.
这篇关于没有数据库的 Django 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!