問題描述
我正在測試一個從另一個非常復(fù)雜的類繼承的類,具有數(shù)據(jù)庫連接方法和一堆依賴項.我想模擬它的基類,以便我可以很好地使用子類中定義的方法,但是在我從模擬類繼承的那一刻,對象本身變成了模擬并丟失了它的所有方法.
I am testing a class that inherits from another one very complex, with DB connection methods and a mess of dependences. I would like to mock its base class so that I can nicely play with the method defined in the subclass, but in the moment I inherit from a mocked class, the object itself turns a mock and loses all its methods.
如何模擬超類?
這種情況或多或少可以概括為:
More or less the situation can be summed up in this:
import mock
ClassMock = mock.MagicMock()
class RealClass(ClassMock):
def lol(self):
print 'lol'
real = RealClass()
real.lol() # Does not print lol, but returns another mock
print real # prints <MagicMock id='...'>
這是一個簡化的案例.實際發(fā)生的是 RealClass
擴展了 AnotherClass
,但我設(shè)法攔截了 AnotherClass
并將其替換為模擬.
This is a simplified case. What is actually happening is that RealClass
extends AnotherClass
, but I managed to intercept the AnotherClass
and replace it with a mock.
推薦答案
這應(yīng)該適合你.
import mock
ClassMock = mock.MagicMock # <-- Note the removed brackets '()'
class RealClass(ClassMock):
def lol(self):
print 'lol'
real = RealClass()
real.lol() # Does not print lol, but returns another mock
print real # prints <MagicMock id='...'>
您不應(yīng)該像以前那樣傳遞類的實例.mock.MagicMock
是一個類,所以你直接傳遞它.
You should'nt pass an instance of the class as you did. mock.MagicMock
is a class, so you pass it directly.
In [2]: inspect.isclass(mock.MagicMock)
Out[2]: True
這篇關(guān)于Python mock:模擬繼承的基類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!