[英]How to mock a method inside another method with Python unittest?
I am struggling to mock a method inside another method ie Let's say I have 2 classes A, B as follows:我正在努力在另一个方法中模拟一个方法,即假设我有 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)
Here I want to mock method_A while testing method_B but can't find a way.在这里,我想在测试method_B时模拟method_A但找不到方法。 Thanks in advance
提前致谢
I hope this is what you are looking for.我希望这就是你要找的。
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'
What exactly do you mean by mocking a method? mocking 方法到底是什么意思? If you mean why your code isn't doing anything that's because you need to call the method afterwards:-
如果您的意思是为什么您的代码没有做任何事情,那是因为您需要在之后调用该方法:-
B.method_B()
Maybe that helps somehow, if not could you explain the problem a lil'bit more.也许这会有所帮助,如果不是,您能否再解释一下这个问题。
Well in that case first you wanna import mock library by simply typing import mock
那么在这种情况下,首先你想通过简单地输入
import mock
来导入模拟库
then you wanna create a function for 1) Mocking那么你想为 1) Mocking 创建一个 function
def mocking_method_A(self):
return Some_value
2)Testing 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.