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

单元测试使用Mock时触发AttributeError:对象无对应属性的问题求助

单元测试使用Mock时触发AttributeError:对象无对应属性的问题求助

大家好,我最近在写单元测试,想要断言A类的foo方法里确实调用了B类的bar方法,但在用Mock模拟的时候遇到了报错,错误信息是:AttributeError: 'A' object has no attribute 'b',报错的位置在A.foo方法里的self.b.bar()这一行。

我把问题简化成了下面的代码片段,方便大家复现问题:

首先是A类的代码:

class A:
   def __init__(self, has_b=True):
      if has_b:
         self.b = b()
   def foo(self):
      return self.b.bar()

然后是B类和创建B实例的函数:

class B:
   def __init__(self):
      pass
   def bar(self):
      return True

# Outside the B class:
def b() -> B:
   return B()

最后是我的单元测试代码:

# Unit Test 
class TestA(TestCase):
   def setUp(self):
      self.mock_b_methods = mock.MagicMock()
      self.A = A()
   def test_foo(self):
      self.mock_b_methods.bar.return_value = True
      res = self.A.foo()
      assertTrue(res)

麻烦各位帮我看看问题出在哪,怎么才能正确Mock并完成这个断言呢?

备注:内容来源于stack exchange,提问作者Mar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:29:30