How To Mock Just The Method Inside The Class
Trying to write a testcase for my class based function. This is skeleton of my class class Library(object): def get_file(self): pass def query_fun(self): p
Solution 1:
You need to take into account you mocked the whole class. You can mock individual methods too:
@mock.patch('library.library.Library.query_fun')deftest_get_response(self, mock_query_fun):
mock_query_fun.return_value = {
'text': 'Hi',
'entities': 'value'
}
}
response = MockBotter.get_response()
self.assertIsNotNone(response)
Only Library.query_fun
has been replaced, everything else in the class is still in place.
Simplified demo:
>>>from unittest import mock>>>classLibrary(object):...defquery_fun(self):...pass...defget_response(self):...return self.query_fun()...>>>with mock.patch('__main__.Library.query_fun') as mock_query_fun:... mock_query_fun.return_value = {'foo': 'bar'}...print(Library().get_response())...
{'foo': 'bar'}
Solution 2:
I have used similar code below in my code, in case you want to mock the constructor too.
from unittest.mock import Mock
@mock.patch('library.library.Library')deftest_get_response(self, MockLibrary):
mock_query_fun = Mock()
mock_query_fun.return_value = {
'text': 'Hi',
'entities': 'value'
}
MockLibrary.return_value = Mock(
query_fun=mock_query_fun
)
...
Post a Comment for "How To Mock Just The Method Inside The Class"