如何使用unittest.mock.patch Mock外部库的实例属性方法调用?
解决unittest.mock.patch无法mock实例属性中外部库方法的问题
你的问题出在Foo类初始化时直接将os模块赋值给了实例属性os_handle,导致后续patch全局os模块无法影响已创建实例的os_handle引用。下面提供两种可行的解决方案:
方案一:直接mock实例的os_handle.getNothing方法
在创建Foo实例后,针对实例的os_handle属性中的getNothing方法进行patch,精准覆盖目标调用:
def testLibraryCallNoException(self): foo = Foo() # patch实例的os_handle.getNothing方法 with patch.object(foo.os_handle, 'getNothing') as mock_get: mock_get.return_value = "mock result" # 设置返回值,避免触发异常 foo.path() self.assertEqual(foo.string, "circumvented the faulty os_handle method call")
方案二:先patch全局os模块的方法再实例化Foo
如果在实例化Foo之前就patch os.getNothing,Foo初始化时赋值的self.os_handle会指向被patch后的os模块,自然就能mock到目标方法:
@patch('os.getNothing') def testLibraryCallNoException(self, mock_get): mock_get.return_value = "mock result" # 此时实例化Foo,self.os_handle会引用被patch后的os模块 foo = Foo() foo.path() self.assertEqual(foo.string, "circumvented the faulty os_handle method call")
为什么你之前的写法无效?
你尝试的@patch('os', 'getNothing', ...)写法错误,patch的第一个参数需要是要mock的对象的完整路径,单个方法的正确路径格式是模块名.方法名(比如os.getNothing),而非将模块和方法分开传递。
内容的提问来源于stack exchange,提问作者hewi
相关产品推荐
相关产品推荐

