有没有办法在TestCase外部使用TestCase.assertEqual()?

3 投票
2 回答
2595 浏览
提问于 2025-04-15 14:36

我有一个工具类,里面存放了一些对单元测试很有用的方法。我希望这些辅助方法能够进行断言(asserts)或失败(fails)等操作,但似乎我不能使用这些方法,因为它们的第一个参数需要是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: unbound method failUnless() must be called with TestCase instance as first argument (got bool instance instead)

2 个回答

4

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

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")
1

听起来你想要这个,至少从错误信息来看是这样的……

unittest_foo.py:

import unittest
from common_methods import *

class TestPayments(unittest.TestCase):
    def test_0(self):
        common_method1(self, "foo")

common_methods.py:

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

撰写回答