0

我现在正在使用 Kent Beck 编写的示例测试驱动开发通过 python 练习 TDD。根据示例,我编写了与 TDDBE 中的示例相同的代码。

class TestCase:
    def __init__(self, name):
        self.name = name

    def run(self):
        exec "self." + self.name + "()"

class WasRun:
    def __init__(self, name):
        self.wasRun = None
        TestCase.__init__(self, name)

    def testMethod(self):
        self.wasRun = 1

test = WasRun("testMethod")
print test.wasRun
test.run()
print test.wasRun

但是当我运行这段代码时,我发现了下面的错误信息。

Traceback (most recent call last):
  File "/Users/sanghee/PycharmProjects/test/test.py", line 17, in <module>
    test = WasRun("testMethod")
  File "/Users/sanghee/PycharmProjects/test/test.py", line 11, in __init__
    TestCase.__init__(self, name)
TypeError: unbound method __init__() must be called with TestCase instance as first argument (got WasRun instance instead)

Process finished with exit code 1

你能告诉我有什么问题吗?为什么?

4

1 回答 1

1

使WasRun类成为 的子类TestCase

class WasRun(TestCase):

现在self是 (a subclass of) 的一个实例TestCase

请注意,您引用的代码并不完全是最佳实践;我会重写它以至少使用新样式的类,用于super()调用超类初始化程序,并避免exec语句:

class TestCase(object):
    def __init__(self, name):
        self.name = name

    def run(self):
        getattr(self, self.name)()

class WasRun(TestCase):
    def __init__(self, name):
        self.wasRun = False
        super(WasRun, self).__init__(name)

    def testMethod(self):
        self.wasRun = True
于 2013-09-17T18:26:42.330 回答