簡體   English   中英

Python unittest setUpClass 無法從基類調用方法

[英]Python unittest setUpClass cannot call method from base class

我正在使用 Python 中的 unittest 框架,並在為測試用例設置類時遇到問題。 我想從 setUpClass() 方法中的基類調用一個方法,如下所示:

class TestA(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestA, self).__init__(*args, **kwargs)

        self.variable = "hello"

    def do_something(self):
        print(self.variable)
        return self.variable

class TestB(TestA.TestA):

    @classmethod
    def setUpClass(cls):

        var = cls.do_something()

但是我收到一個錯誤,說我不能調用 do_something()。

TypeError: unbound method do_something() must be called with TestB instance as first argument (got nothing instead)

我不知道如何(以及是否)可以從基類調用方法作為 setUpClass 方法的一部分。

我錯過了什么?

使用super()

>>> class Base:
...     def do(self):
...             print('base is doing something')
... 
>>> class Child(Base):
...     def better_do(self):
...             super().do()
...             print('much better')
... 
>>> 
>>> c = Child()
>>> c.do()
base is doing something
>>> c.better_do()
base is doing something
much better
>>> 

然而,類方法有點不同。 您必須調用類本身。

>>> class Base:
...     @classmethod
...     def cls_do(cls):
...             print('Base class is doing something')
... 
>>> Base.cls_do()
Base class is doing something
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM