1

我用我自己的类覆盖unittest.TestCase,我想在其中添加一些额外的功能assertEqual

class MyTestCase(unittest.TestCase):        
    def __init__(self,*args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

    def _write_to_log(self):
        print "writing to log..."

    def assertEqual(self, first, second, msg=None):
        self._write_to_log()
        unittest.TestCase.assertEqual(first, second, msg)

但我得到了TypeError: unbound method assertEqual() must be called with TestCase instance as first argument (got int instance instead)

4

2 回答 2

2

您忘记传递selfassertEqual

unittest.TestCase.assertEqual(self, first, second, msg)

您应该super()在整个覆盖过程中真正使用:

class MyTestCase(unittest.TestCase):        
    def __init__(self,*args, **kwargs):
        super(MyTestCase, self).__init__(*args, **kwargs)

    def assertEqual(self, first, second, msg=None):
        self._write_to_log()
        super(MyTestCase, self).assertEqual(first, second, msg)
于 2013-04-12T15:59:18.017 回答
1

assertEqual作为类方法调用,而不传递实例:这就是 Python 抱怨该方法未绑定的原因。

您可能应该使用:

super(MyTestCase, self).assertEqual(first, second, msg)
于 2013-04-12T15:56:57.590 回答