简体   繁体   中英

mocking and testing a single method in the class (MagicMock/py.test)

I want to write a test for a single method in class (let's say it is a 'str' class):

   mocked_str = mock.MagicMock(str)
   str.__len__(mocked_str)

But it fails:

TypeError: descriptor '__len__' requires a 'str' object but received a 'MagicMock'

How can I mock whole class except a single function from it (for testing)? Thanks.

It looks like you have it the wrong way around. mocked_str is the object you just mocked and __len__ is the mocked method on it:

>>> mocked_str.__len__('foo')
0 

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