【问题标题】:Using a TestCase subclass in another unit test in Python在 Python 的另一个单元测试中使用 TestCase 子类
【发布时间】:2017-12-18 09:18:29
【问题描述】:

这是一个例子:

from unittest import TestCase


class DogTest(TestCase):

    def create_dog(self, weight):

        dog = {'weight': weight}

        return dog


class DogPawTest(TestCase):

    def test_dog_paw(self):

        dog_test = DogTest()
        dog = dog_test.create_dog(weight=10)
        self.assertEqual(dog['weight'], 10)

它抛出

ValueError: no such test method in <class 'unittest_case_import.DogTest'>: runTest

测试用例应该是独立的。此外,create_dog 可以而且应该在测试类之外。将定义更改为DogTest(object) 即可解开谜团。但我有一个案例,它不是一个选项。

如何在test_dog_paw 中使用另一个基于TestCase 的类的方法?

【问题讨论】:

  • 您可以在 DogPawTest 中使用DogPawTest(DogTest)。并使用self.create_dog(weight=10
  • @ManojJadhav 唉,就我而言,我必须在一个类中导入多个 TestCase 类。 Mixins 可能会有所帮助,但它需要大量重构。

标签: python unit-testing inheritance subclass python-unittest


【解决方案1】:

对于您提供的示例,我认为不需要继承。您可以轻松地执行以下操作:

from unittest import TestCase

def create_dog(weight):
    return {'weight': weight}

class DogTest(TestCase):
    def test_dogs(self):
        heavy_dog = create_dog(25)
        ...

class DogPawTest(TestCase):
    def test_dog_paw(self):
        dog = create_dog(weight=10)
        self.assertEqual(dog['weight'], 10)

也值得看看 PyTest 的 fixtures 之类的东西。这可能会将此代码更改为:

from unittest import TestCase
import pytest

@pytest.fixture
def dog():
    """Just your regular average dog"""
    return {'weight': 15}

@pytest.fixture
def heavy_dog():
    return {'weight': 30}

@pytest.fixture
def light_dog():
    return {'weight': 10}

class DogTest(TestCase):
    def test_dogs(self, heavy_dog):
        ...

class DogPawTest(TestCase):
    def test_dog_paw(self, dog):
        self.assertEqual(dog['weight'], 10)

【讨论】:

  • 谢谢!我有强制我继承的代码,所以我一直在寻找创建已建立测试用例实例的捷径。
  • 好吧,我猜我的答案并不适用。
猜你喜欢
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多