I am struggling to mock a method inside another method i.e Let's say I have 2 classes A, B as follows:
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. Thanks in advance
-
Are you trying to test method_B by mocking mothod_A?Akalanka Weerasooriya– Akalanka Weerasooriya2020年05月22日 09:39:00 +00:00Commented May 22, 2020 at 9:39
-
Yes, I want to test method_B by mocking method_A.unitSphere– unitSphere2020年05月22日 09:40:35 +00:00Commented May 22, 2020 at 9:40
3 Answers 3
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'
Comments
What exactly do you mean by mocking a method? 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.
Comments
Well in that case first you wanna import mock library by simply typing import mock
then you wanna create a function for 1) Mocking
def mocking_method_A(self):
return Some_value
2)Testing
def testing_method_B():
with mock.patch.object(A, 'method_A', new=mocking_A):
result = B().method_B()
assert result == Some_value