python - 无论如何在 TestCase 之外使用 TestCase.assertEqual() ?

标签 python unit-testing

我有一个实用程序类,它存储对某些单元测试用例有用的方法。我希望这些辅助方法能够执行断言/失败/等等,但似乎我不能使用这些方法,因为它们期望 TestCase 作为它们的第一个参数...

我希望能够将常用方法存储在测试用例代码之外,并继续在其中使用断言,这可能吗?它们最终用于测试用例代码。

我有这样的东西:

unittest_foo.py:

import unittest
from common_methods import *
class TestPayments(unittest.TestCase):
 def test_0(self):
  common_method1("foo")

common_methods.py:

from unittest import TestCase
def common_method1():
    blah=stuff
    TestCase.failUnless(len(blah) > 5)
        ...
...

套件运行时:

TypeError:未绑定(bind)方法 failUnless() 必须以 TestCase 实例作为第一个参数调用(取而代之的是 bool 实例)

最佳答案

这通常是通过多重继承来实现的:

common_methods.py:

class CommonMethods:
  def common_method1(self, stuff):
    blah=stuff
    self.failUnless(len(blah) > 5)
        ...
...

unittest_foo.py:

import unittest
from common_methods import CommonMethods
class TestPayments(unittest.TestCase, CommonMethods):
 def test_0(self):
  self.common_method1("foo")

关于python - 无论如何在 TestCase 之外使用 TestCase.assertEqual() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480144/

相关文章:

c++ - 测试 C++ 迭代器

python - Django 请求查找以前的推荐人

python - Celery - 内存泄漏(即使工作人员完成任务后内存也不会释放)

python - 尝试创建 AI - 某些 IF 语句未捕获

django - 在 Django 的基于类的 View 中模拟函数

unit-testing - 私有(private)方法 使用 Jasmine 进行单元测试

python - 根据 2 个条件替换 Df 中的值

python - 如何生成以文本作为 ytick 标签的绘图

unit-testing - 单元测试抽象类和/或接口(interface)

javascript - 是否有任何 QUnit 断言/函数来测试元素是否在数组中