且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模拟通过实例使用的类方法

更新时间:2023-10-21 21:37:40

我发现了我的错误:为了配置模拟实例的方法,我必须使用mock().method而不是mock.method.

I have found my error: In order to configure the methods of my mock's instances, I have to use mock().method instead of mock.method.

class Lib:
    """In my actual program, a module that I import"""
    def method(self):
        return "real"

class User:
    """The class I want to test"""
    def run(self):
        l = Lib()
        return l.method()

with patch("__main__.Lib") as mock:
    #mock.return_value = "bla" # This works
    mock().method.return_value = "mock"
    u = User()
    print(u.run())