Class A has an attribute of another class B.
Class A():
def __init__(self, b):
self.b = b
def get_b_secret(self, job_id):
x, y = self.b.get_secret(job_id)
return x, y
Class B():
def __init__(self, key, url):
self.key = key
self.url = url
def get_secret(job_id):
# logic to get secret
# return a tuple
return x, y
I want to write a unit test for method get_b_secret
of class A by mocking B class as a whole.
@patch('b.B')
def test_get_b_secret(self, mock_b):
mock_b.b.get_secret.return_value = ('x', 'y')
obj = A(mock_b)
expected = ('x','y')
self.assertEqual(obj.get_b_secret('001'), expected)
I realized that by mocking class B, I am not really instantialzing B to an instance inside of A's instance. That's why when I debug the test, A
's get_b_secret
is returning a MagicMock
object instead.
I found this article about mocking object. But in that example, the outer class's init doesn't have inner Class object as an argument. So it is a little different. What is the best way to do it?
question from:
https://stackoverflow.com/questions/65838289/how-to-create-an-instance-of-mocked-class-within-another-class 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…