我已經寫了一段代碼,使用一個配置文件(以JSON格式)單元測試 - assertRaises返回一個錯誤,而不是通過
def test_read_config_file(self):
self.assertRaises(ValueError, self.read_config_file('no_json.txt')
原有的功能看起來像這樣的:
def read_config_file(file_name)
config_data = None
try:
with open(file_name, 'r') as infile:
config_data = json.load(infile)
except ValueError as err:
LOGGER.error(str(err))
return config_data
當我跑我的測試用例我得到這個:
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded
no_json.txt只包含 「嗨」。爲什麼我在這裏得到4錯誤?
感謝,
能有什麼辦法? 「你好」是無效的JSON,所以錯誤被記錄。它似乎不是測試結果。相反,它看起來像一個印刷品。 – Sadik
在文檔中有一個使用'with'語句處理斷言的例子。你的'read_config_file'函數也通過記錄來處理異常。如果你希望你的函數在記錄後提高ValueError,那麼你應該在異常子句中記錄後寫'raise'來重新提高它。 –
@Zazz你應該接受一個答案,如果它幫助你。 – Wombatz