[英]Mocking ConfigObj instances
def create_section(config, section):
config.reload()
if section not in config:
config[session] = {}
logging.info("Created new section %s.", section)
else:
logging.debug("Section %s already exists.", section)
我想寫幾個單元測試,但我遇到了問題。 例如,
def test_create_section_created():
config = Mock(spec=ConfigObj) # ← This is not right…
create_section(config, 'ook')
assert 'ook' in config
config.reload.assert_called_once_with()
顯然,測試方法因TypeError
而失敗,因為'Mock'類型的參數不可迭代。
如何將config
對象定義為模擬?
這就是為什么你應該永遠, 永遠 ,后在你面前是很清醒:
def test_create_section_created():
logger.info = Mock()
config = MagicMock(spec=ConfigObj) # ← This IS right…
config.__contains__.return_value = False # Negates the next assert.
create_section(config, 'ook')
# assert 'ook' in config ← This is now a pointless assert!
config.reload.assert_called_once_with()
logger.info.assert_called_once_with("Created new section ook.")
我將把這個答案/問題留給后人,以防萬一其他人有腦衰...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.