![](/img/trans.png)
[英]Python unittest mock method which called in another module work error
[英]How to mock a method inside another method with Python unittest?
我正在努力在另一个方法中模拟一个方法,即假设我有 2 个类 A、B,如下所示:
class A:
def method_A(self):
return "Hi"
class B:
def method_B(self):
instance_A = A()
result = instance_A.method_A()
print(result)
在这里,我想在测试method_B时模拟method_A但找不到方法。 提前致谢
我希望这就是你要找的。
class A:
def method_A(self):
return "Hi"
class B:
def method_B(self):
instance_A = A()
result = instance_A.method_A()
return result
import mock
def mock_A(self):
return 'Bye'
def test_method_B():
with mock.patch.object(A, 'method_A', new=mock_A):
result = B().method_B()
assert result == 'Bye'
mocking 方法到底是什么意思? 如果您的意思是为什么您的代码没有做任何事情,那是因为您需要在之后调用该方法:-
B.method_B()
也许这会有所帮助,如果不是,您能否再解释一下这个问题。
那么在这种情况下,首先你想通过简单地输入import mock
来导入模拟库
那么你想为 1) Mocking 创建一个 function
def mocking_method_A(self):
return Some_value
2)测试
def testing_method_B():
with mock.patch.object(A, 'method_A', new=mocking_A):
result = B().method_B()
assert result == Some_value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.