如何 mock.patch 在另一个模块中导入的类 [英] How to mock.patch a class imported in another module

查看:27
本文介绍了如何 mock.patch 在另一个模块中导入的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这样模块的 python 类:

I have a python class with such a module:

xy.py

from a.b import ClassA

class ClassB:
  def method_1():
    a = ClassA()
    a.method2()

然后我将 ClassA 定义为:

then I have ClassA defined as:

b.py

from c import ClassC

class ClassA:
  def method2():
      c = ClassC()
      c.method3()

现在在这段代码中,在为 xy.py 编写测试时我想模拟.patch ClassC,有没有办法在 python 中实现它?

Now in this code, when writing test for xy.py I want to mock.patch ClassC, is there a way to achieve that in python?

显然我试过了:

mock.patch('a.b.ClassA.ClassC')

mock.patch('a.b.c.ClassC')

这些都没有用.

推荐答案

你需要修补 ClassC 所在的位置,这样 ClassCb>:

You need to patch where ClassC is located so that's ClassC in b:

mock.patch('b.ClassC')

或者,换句话说,ClassC 被导入到模块 b 中,所以这是 ClassC 需要修补的范围.

Or, in other words, ClassC is imported into module b and so that's the scope in which ClassC needs to be patched.

这篇关于如何 mock.patch 在另一个模块中导入的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆