Django. TestCase未运行

2 投票
2 回答
1411 浏览
提问于 2025-04-17 15:44

为什么我在终端运行 python manage.py test appname 时,结果是:运行了 0 个测试,耗时 0.000 秒,OK?

这是我的 tests.py:

from django.test import TestCase
import appname.factories

class UserProfileTest(TestCase):
    def sample_data(self):
        for i in range(0, 10):
            user = appname.factories.UserProfileFactory.create()

这是我的 models.py:

from django.db import models

class UserProfile(models.Model):
    street = models.CharField(max_length=250)
    tel = models.CharField(max_length=64, default='', blank=True)
    postcode = models.CharField(max_length=250)

    def __unicode__(self):
        return self.tel

这是我的 factories.py(使用 factory boy):

from appname.models import *
import factory


class UserProfileFactory(factory.Factory):
    FACTORY_FOR = UserProfile

    street = factory.Sequence(lambda n: 'Street' + n)
    tel = factory.Sequence(lambda n: 'Tel' + n)
    password = 'abcdef'

2 个回答

2

test.py 是错误的,应该是 tests.py

关于编写测试的说明在文档中提到

对于一个Django应用,测试运行器会在两个地方寻找单元测试:

  • 在 models.py 文件中。测试运行器会在这个模块中寻找任何继承自 unittest.TestCase 的子类。
  • 在应用目录下的一个叫做 tests.py 的文件——也就是存放 models.py 的那个目录。同样,测试运行器会在这个模块中寻找任何继承自 unittest.TestCase 的子类。
5

你的每个测试函数都应该以“test”这个词开头。

你需要把函数 def sample_data(self): 改成 def test_sample_data(self):

测试运行器会在一个叫 tests.py 的文件里寻找任何类,这个文件放在你应用的根目录下,并且这些类要继承 unittest.TestCase。然后,它会运行这个类中所有以“test”开头的函数(还有一两个其他的函数,比如 setup())。

我可能说得不太清楚,但我在Django的主要测试文档中没有看到任何说明说函数必须以“test”开头。不过,在这个(官方)教程中提到了这个要求。

撰写回答