Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65838289/how-to-create-an-instance-of-mocked-class-within-another-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...