問題描述
在我的 python 代碼中,我檢查其中一個參數的類型以確保它是我期望的類型.例如:
In my python code I check the type of one of the parameters to make sure it is of the type I expect. For instance:
def myfunction(dbConnection):
if (type(dbConnection)<>bpgsql.Connection):
r['error'] += ' invalid database connection'
我想傳遞一個模擬連接以進行測試.有沒有辦法讓模擬對象偽裝成正確的類型?
I want to pass a mock connection for testing purposes. Is there a way to make the mock object pretend to be of the correct type?
推薦答案
恕我直言,看來你們不太對勁!
With all due respect, It looks like you guys are not quite right!
如上所述,我可以使用鴨子打字,但有一種方法可以做我最初打算做的事情:
I can use duck typing as said, but there is a way to do what I intended to do in the first place:
來自 http://docs.python.org/dev/library/unittest.mock.html
使用類或實例作為 spec
或 spec_set
的模擬對象能夠通過 isintance 測試:
Mock objects that use a class or an instance as a spec
or spec_set
are able to pass isintance tests:
>>>
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
所以我的示例代碼如下:
so my example code would be like:
m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection)
返回真
話雖如此,我并不是在爭論在 python 中進行嚴格的類型檢查,我說如果你需要檢查它你可以做到,它也適用于測試和模擬.
All that said, I am not arguing for strict type checking in python, I say if you need to check it you can do it and it works with testing and mocking too.
這篇關于我可以在 python 單元測試中偽造/模擬我的模擬對象的類型嗎的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!