【问题标题】:How can i mock __init__ in python我如何在 python 中模拟 __init__
【发布时间】:2021-02-18 12:17:25
【问题描述】:

这是我的班级结构。

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.
        
        
    

我怎样才能做到这一点?

【问题讨论】:

  • 这能回答你的问题吗? Mocking __init__() for unittesting。看第二个答案
  • 这有点太小了;首先,您是否有理由需要一个包装器来创建 DataLoader 实例?我会尽量避免这种情况,所以没有必要嘲笑。

标签: python


【解决方案1】:

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

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 函数作为 __init__ 的模仿添加到那里,因为它们有 3 个参数并且它们返回 None

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 2016-04-27
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多