使用python unittest.mock如何模拟来自我的一个库中创建的外部库的对象?
我正在为我的Python项目创建一些测试,但是我有一个问题创建一个UnitTest.patch
my_project.py
from service.my_service import Service
def main():
token = '123456'
my_service = Service(token)
# calls to my service
service/my_service.py
from external_library import Client
class Service:
def __init__(self, token):
self.__client = Client(token)
#Methods that interacts with self.__client (the one I want to mock)
我想测试main()函数仅模拟external_library.client.client
为此,我创建了此测试:
test/test_main,
from unittest.mock import patch
@patch('my_project.Service.Client')
def test_main(client_mock):
...
main()
但是当它试图修补一个服务/my_service/service时,它失败了,没有属性“客户端”。
问题是什么,我该如何模拟此客户端对象?
I'm creating some test for my python project but I have a problem creating a unittest.patch
my_project.py
from service.my_service import Service
def main():
token = '123456'
my_service = Service(token)
# calls to my service
service/my_service.py
from external_library import Client
class Service:
def __init__(self, token):
self.__client = Client(token)
#Methods that interacts with self.__client (the one I want to mock)
I would like to test the main() function mocking only the external_library.Client
To do so I created this test:
test/test_main
from unittest.mock import patch
@patch('my_project.Service.Client')
def test_main(client_mock):
...
main()
But it fails when it tries to patch saying that service/my_service/Service does not have the attribute 'Client'.
What is the issue and how can I mock this Client object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论