繁体   English   中英

我如何在 python 中模拟 __init__

[英]How can i mock __init__ in python

这是我的 class 结构。

class DataLoader:
    #some stuff
    
class ABC:
    def get_loader(key1, key2)
        loader = DataLoader(key1, key2)
        return loader

class TestABC:
    def setUp():
        self.obj =  ABC()
    
    def test_get_loader()
        ret = self.obj.get_loader(1, 2)  # here I don't want to call actual DataLoader, instead mocked DataLoader should be return.
        
        
    

我怎样才能做到这一点?

我之前偶然发现的最好方法之一是下面的这个(如果有人记得参考资料,给他们学分会很棒):

with patch.object(DataLoader, "__init__", lambda x, y, z: None):
    ret=DataLoader(None,#insert as many None as the number of your constructor arguments in dataloader that you want to be set to None, else insert your values)
    #you can access its properties with:
    var=ret.name_of_property
    #you can use assert to test
    assert ret.function(arg1,arg2)==value

lambda function 作为__init__的模仿被添加到那里,因为它们都有 3 个 arguments 并且它们返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM