使用python unittest.mock如何模拟来自我的一个库中创建的外部库的对象?

发布于 2025-02-12 01:29:42 字数 801 浏览 0 评论 0原文

我正在为我的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文