[英]How can i mock __init__ in python
This is my class structure.这是我的 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.
How can I achieve that?我怎样才能做到这一点?
One of the best ways i've stumbled upon before is this one below (if someone remembers the reference it would be great to give them credits):我之前偶然发现的最好方法之一是下面的这个(如果有人记得参考资料,给他们学分会很棒):
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
The lambda function is added there as an imitation of the __init__
since they have both 3 arguments and they return None
. lambda function 作为
__init__
的模仿被添加到那里,因为它们都有 3 个 arguments 并且它们返回None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.