用类的存根替换类

2024-09-29 23:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下示例代码:

class AuxiliaryClass:
    @staticmethod
    def high_cost_method():
        "Do something"

class MyTestedClass:
    def do_something(self):
        something = AuxiliaryClass.high_cost_method()
        "do something else"

我想测试MyTestedClass。为此,我创建了AuxiliaryClassStub类来重写high_cost_method()。我希望我的测试从MyTestedClass执行do_something(),但是do_something()应该使用存根而不是实类。
我该怎么做?
我真正的辅助类很大,它有很多方法,我会在很多测试中使用它,所以我不想修补单个方法。我需要在考试时替换全班同学。你知道吗

请注意,high_cost_method()是静态的,因此在这种情况下模拟__init__()__new__()将没有帮助。你知道吗


Tags: 方法代码self示例defdomethodsomething
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:27

如果在do_something中使用self.__class__.high_cost_method,它能工作吗?这样就避免了对类名的直接引用,这将启用子类化,并用AuxiliaryClass中的方法重写staticmethod。你知道吗

class MyTestedClass:
    def do_something(self):
        something = self.__class__.high_cost_method()
        something()

    @staticmethod
    def high_cost_method():
        print("high cost MyTestedClass")


class AuxiliaryClass(MyTestedClass):
    @staticmethod
    def high_cost_method():
        print("high cost AuxiliaryClass")

然后你得到

test = AuxiliaryClass()
test.high_cost_method()

high cost AuxiliaryClass

否则呢

test = MyTestedClass()
test.high_cost_method()

high cost MyTestedClass

相关问题 更多 >

    热门问题