[英]Mocking - How do I raise exception on the caller?
假設這是代碼
def move(*args, **kwargs):
try:
shutil.move(source, destination)
except Exception as e:
raise e
在我的tests.py中
@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_rmtree):
''' Tests moving a target hits exception. '''
mock_rmtree.side_effect = Exception('abc')
self.assertRaises(Exception, move,
self.src_f, self.src_f, **self.kwargs)
它說這個
File "unittests.py", line 84, in test_move_catch_exception
self.src_f, self.src_f, **self.kwargs)
AssertionError: Exception not raised
如果我在mock_rmtree
斷言它將通過。 如何在調用者上斷言(在這種情況下,函數move
)?
如aquavitae所指出的,主要原因是復制粘貼錯誤,而且我在開始時也斷言了一個元組。 始終使用正確的返回類型...
你的例子中有一個拼寫錯誤,錯過了'
。
它並不完全清楚你在問什么,但是如果我理解你的話,你就會問如何測試一個被引發的異常被move
到內部。 一個問題是你正在修補shutil.rmtree
,而不是shutil.move
,但你無法確定是否會調用shutil.rmtree
。 如果成功復制目錄, shutil.move
實際上只調用shutil.rmtree
,但由於你將self.src_f
復制到自身,所以不會發生這種情況。 這不是修補它的一種非常好的方法,因為假設shutil.move
不會調用shutil.rmtree
並且是依賴於實現的。
至於如何測試它,只需檢查返回值是否符合預期:
@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_move):
''' Tests moving a target hits exception. '''
e = OSError('abc')
mock_move.side_effect = e
returns = move(self.src_f, self.src_f, **self.kwargs)
assert returns == (False, e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.