简体   繁体   中英

How to create an instance of mocked class within another class

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?

If you example code is correct, than you don't need to mock class B. You just need to pass mock with function get_secret into class A when you initializing it.

mock = MagicMock()    

mock.return_value.get_secret.return_value = ('x', 'y')
obj = A(mock)
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM