You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python单元测试Mock导入模块中get_service函数失效问题咨询

问题原因和修复方案

首先排查基础语法和导入问题:

  • 你给出的app_module代码中class ServiceProvider()定义后缺少语法必须的冒号:,先修正该语法错误
  • 测试文件需要补全缺失的导入:
    import unittest
    from unittest.mock import patch
    # 补充你自己定义的ServiceA、ServiceB类的导入
    from your_module import ServiceA, ServiceB
    from app_module import ServiceProvider
    

如果基础问题修正后还是调用原始函数,核心是mock路径匹配问题,Python的mock遵循哪里使用就在哪里mock的原则:
你当前写的patch('app_module.get_service')路径逻辑是正确的,如果不生效大概率是路径匹配不准,可以按以下优先级排查:

  1. 优先改用全绝对路径写patch参数,比如你的app_module在项目的core包下,就改为:
    with patch('core.app_module.get_service') as mocked_get_service:
    
  2. 如果还是不生效,可以用手动替换的方式更稳妥,不会受路径解析影响:
    def test1_find_service(self):
        import app_module
        # 先保存原始函数用于测试后恢复
        original_get_service = app_module.get_service
        app_module.get_service = mock_get_service
        try:
            server = ServiceProvider()
            serv = server.find_service('ServiceA')
            self.assertIsInstance(serv, ServiceA)
        finally:
            # 恢复原始函数,避免影响其他用例
            app_module.get_service = original_get_service
    
  3. 额外注意:不要在测试代码的顶部提前从app_module导入get_service,否则导入的是原始函数的引用,mock不会替换你提前导入的变量。

内容的提问来源于stack exchange,提问作者sisyphus_64

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:24:03