問題描述
我有一個要單元測試的函數包含調用其他兩個函數.我不確定如何使用補丁正確地同時模擬這兩個函數.我在下面提供了一個例子來說明我的意思.當我運行nosetests時,測試通過了,但我覺得必須有一種更清潔的方法來做到這一點,我并不真正理解關于f.close()的文章......
I have a function I want to unit test contains calls two other functions. I am unsure how can I mock both functions at the same time properly using patch. I have provided an example of what I mean below. When I run nosetests, the tests pass but I feel that there must be a cleaner way to do this and I do not really Understand the piece regarding f.close()...
目錄結構如下:
program/
program/
data.py
tests/
data_test.py
數據.py:
import cPickle
def write_out(file_path, data):
f = open(file_path, 'wb')
cPickle.dump(data, f)
f.close()
data_test.py:
data_test.py:
from mock import MagicMock, patch
def test_write_out():
path = '~/collection'
mock_open = MagicMock()
mock_pickle = MagicMock()
f_mock = MagicMock()
with patch('__builtin__.open', mock_open):
f = mock_open.return_value
f.method.return_value = path
with patch('cPickle.dump', mock_pickle):
write_out(path, 'data')
mock_open.assert_called_once_with('~/collection', 'wb')
f.close.assert_any_call()
mock_pickle.assert_called_once_with('data', f)
結果:
$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.008s
OK
推薦答案
您可以通過使用補丁裝飾器并像這樣嵌套它們來簡化測試(默認情況下它們是 MagicMock
對象):
You can simplify your test by using the patch decorator and nesting them like so (they are MagicMock
objects by default):
@patch('cPickle.dump')
@patch('__builtin__.open')
def test_write_out(mock_open, mock_pickle):
path = '~/collection'
f = mock_open.return_value
f.method.return_value = path
write_out(path, 'data')
mock_open.assert_called_once_with('~/collection', 'wb')
mock_pickle.assert_called_once_with('data', f)
f.close.assert_any_call()
對 MagicMock
實例的調用會返回一個新的 MagicMock
實例,因此您可以檢查返回的值是否像任何其他模擬對象一樣被調用.在這種情況下,f
是一個名為 'open()'
的 MagicMock
(嘗試打印 f
).
Calls to a MagicMock
instance return a new MagicMock
instance, so you can check that the returned value was called just like any other mocked object. In this case f
is a MagicMock
named 'open()'
(try printing f
).
這篇關于用補丁模擬兩個函數以進行單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!