我正在编写unittest.TestCase的子类来抽象一些代码细节,并且我想使用自己的assert函数,但是我需要将此assert结果报告给测试结果。我试图重用这样的unittest断言函数:
class MyTestCase(unittest.TestCase):
def assertState(state, value):
if state_dict[state] == value:
self.assertTrue(True)
else:
self.assertTrue(False)
问题是在MyTestCase实例中对asserrState的调用将报告assertError而不是向测试结果对象报告错误。
请建议如何在unittest.TestCase的子类中编写自己的断言函数。
编辑:
我要完成的工作是提供我们自己的MyTestCase类作为基类,其中包含更多具有业务逻辑的断言函数。这样,真实的测试可以仅继承MyTestCase的子类并使用这些断言,而无需重复相同的代码。这意味着我希望能够在MyTestCase的子类中调用MyTestCase.assertState,并且仍然将测试失败报告给该具体测试结果。类似于以下内容。
class ConcreteTestCase(MyTestCase):
def test_1(self):
#do something here
self.assertState("state", "on")
请让我知道是否有办法。
最佳答案
class MyTestCase(unittest.TestCase):
def assertState(self, state, value):
self.assertEqual(value, self.state_dict[state])
def test_whatever(self):
self.assertState(1, 1)
self.assertState(2, 2)
关于python - Python unittest:如何重用TestCase.assert函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5926213/