Python 单元测试 : how to reuse the TestCase. 断言函数

标签 python

我正在写一个unittest.TestCase的子类来抽象我们代码的一些细节,我想使用我自己的断言函数,但是我需要这个断言结果将报告给测试结果。我正在尝试像这样重用单元测试断言函数:

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 单元测试 : how to reuse the TestCase. 断言函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926213/

相关文章:

python - 在 pandas 中创建新列时如何按两个条件进行过滤

python - 按关键字长度对字典进行排序

python - 如何在 dynamodb 中使用两个不同的凭据来拥有只读用户和所有访问用户?

python - 提高 "increment the number represented as an array of digits"的时间复杂度

python - 基于双字母组频率替换单词,Python

python - 使用 Python 在循环中生成列表组合

python - Shell 脚本未在 ubuntu 中运行

python - 如何在Python中编辑表单时为变量赋值

python - 如何使用 Python 截取整个滚动元素的屏幕截图

python - 如何在 Python 中为 Ant 媒体 API 发送发布请求