【问题标题】:Django tests - a test in classA fail when i run classB (which is subclass of classA)Django 测试 - 当我运行 classB(它是 classA 的子类)时,classA 中的测试失败
【发布时间】:2021-02-19 07:36:40
【问题描述】:

我有一个包含多个类的测试套件 - ClassA 和 ClassB。 ClassB 是 classA 的子类,当我运行 classA 测试时,它们都通过了。但是,当我运行 ClassB 时,classA 测试失败。我不确定这是如何或为什么会发生的。

 class ClassA(TestCase):
      def test1(self):
            # run test

      def test2(self):
            # run test


class ClassB(ClassA):

      def test3(self):
            # run test

      def test4(self):
            # run test

python manage.py test app.tests.test_views.ClassA

all pass

python manage.py test app.tests.test_views.ClassB

FAIL: test1 (app.tests.test_views.ClassA)
Test 1
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/test_views.py", line 1435, in test1
    obj.evidence, "This is the evidence entered by user."
AssertionError: 'Generic evidence' != 'This is the evidence entered by user.'
    - Generic evidence
+ This is the evidence entered by user.

这显然是一个简化的示例,我知道最好不要在 ClassB 中子类化 ClassA,但是在我的实际代码中,有 ClassB 测试需要 ClassA 的某些方法。我知道使用固定装置会更好地处理这件事,但目前它是这样设置的,重新设计将是一个很大的改进。

我的理解是,当我执行 ClassB 测试方法时,所有 ClassA 测试都会运行,因为它是子类化的:

python manage.py test app.tests.test_views.ClassA

runs test1 and test2

python manage.py test app.tests.test_views.ClassB

runs test1, test2, test3 and test4

但是,我认为每次运行测试时,数据库都会被清空并重新安装。那么为什么 test1 在运行 ClassA 时会通过,但在 ClassA 测试作为 ClassB 的一部分运行时会失败?

【问题讨论】:

    标签: python django unit-testing testing


    【解决方案1】:

    正如您所了解的,重复在测试中很有用。抽象测试只会使调试复杂化,当出现问题时,您最不想做的就是在调试问题之前先调试测试。

    也就是说,如果您有共享功能,请确保它们不生成数据,如果它们生成数据,它们会自行清理。在您过于简化的情况下,这并不明显,但如果您共享 setUpClass 或 setUpTestData 或夹具类属性,您可能会遇到麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多