首页 > 解决方案 > 当你可以替换一个对象时为什么要模拟?

问题描述

当我可以直接替换我想模拟的对象时,我试图理解为什么我需要使用模拟。

例如在这个人为的例子中

class Child:
    def get(self):
        return {0 : "SomeDictResult"}

class Root:
    def __init__(self):
        self.child = Child()

    def get_info(self):
        return self.child.get()

def test_get_info(root : Root):
    root.child.get = lambda : {1 : "SomeOtherResult"} # This is where a mock would be

    print(root.get_info())

我没有模拟,而是将 get 替换为具有自定义输出的 lambda 函数。get如果我可以替换函数,为什么我需要模拟

标签: pythontestingmockingpytest

解决方案


推荐阅读