用繁琐的__init__模拟类 [英] Mock a class with tedious __init__
问题描述
我有一个实际上连接到服务并进行身份验证和工作的类,但是所有这些都在我的代码中的其他地方经过了很好的测试,我只想在以下测试中进行模拟:
I have a class that actually connects to a service and does authentication and stuff, but all of this is well tested somewhere else in my code, I just want to mock in the following test:
具有繁琐的__init __
class B(object):
def __init__(self, username, password):
con = connect_to_service() #
auth = con.authenticate(username, password)
def upload(self)
return "Uploaded"
class A(object):
def send():
b = B('user', 'pass')
b.upload()
tests.py
# Now, I want here to test A, and since it uses B, I need to mock it, but I can't get it to work.
def test_A():
# Here I need to mock B and B.upload, I tried this:
a = A()
b = Mock()
b.upload.return_value='Hi'
a.send()
但是此测试失败了,因为它到达了B. init 上的auth(),我想成为一个Mock模型.
But this test is failling because it reached auth() on B.init, which I want to be a Mock model.
推荐答案
我认为这是 mock.patch
的典型用例.请注意, patch
装饰器需要主模块成为 __ main __
I think that is a typical use case for mock.patch
. Take care that patch
decorator need the full path of the module where the main module become __main__
from mock import patch, Mock
from abmodule import A, B #Where A and B are
@patch("abmodule.B")
def test_A(bmock):
# Set B costructor to return a Mock object
bmock.return_value = Mock()
bmock.upload.return_value='Hi'
a = A()
a.send()
#Check if upload was called!
bmock.return_value.upload.assert_called_with()
此后,您可以在代码的另一部分再次使用原始的 B
:修补版本仅存在于函数范围之内.
After that you could use use again the original B
in the other part of the code: the patched version live just in scope of the function.
这篇关于用繁琐的__init__模拟类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!