简体   繁体   English

模拟和测试类中的单个方法(MagicMock / py.test)

[英]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): 我想为类中的单个方法编写一个测试(假设它是一个“ str”类):

   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__是其上的模拟方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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