以下是一个例子:
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)
可以解决问题。但我有一个案例,它不是一个选择。
如何在TestCase
中使用其他基于test_dog_paw
的课程的方法?
答案 0 :(得分: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)