2

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

asked May 22, 2020 at 9:28
2
  • Are you trying to test method_B by mocking mothod_A? Commented May 22, 2020 at 9:39
  • Yes, I want to test method_B by mocking method_A. Commented May 22, 2020 at 9:40

3 Answers 3

4

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'
answered May 22, 2020 at 9:57
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered May 22, 2020 at 9:36

Comments

0

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
answered May 22, 2020 at 10:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.