[英]python mock: configure spec of a mock object
我有一個實例方法,它啟動另一個類的對象。 例如,
import module_two
class One:
def start(self):
self.two = module_two.Two()
我正在我的測試用例中修補一個類
@patch('module_one.One', autospec=True)
def test_one(patched_one):
two = patched_one.return_value
# Following method should raise error, but doesn't
two.any_random_non_existing_method()
如前所述, two.any_random_non_existing_method()
不會引發任何錯誤,因為two
Mock 對象沒有分配任何規范。
如何將規范分配給two
對象。? 我正在尋找類似以下代碼段的內容。
# note: configure_spec actually doesn't exist.!
two.configure_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
經過一些評論,看起來mock_add_spec
對你mock_add_spec
:
向模擬添加規范。 spec 可以是一個對象或一個字符串列表。 只有規范上的屬性可以作為屬性從模擬中獲取。
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec
這是它的外觀:
# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.