長話短說,我完全能夠模擬類方法,當它只是被模擬對象取代的方法時,但我無法在我試圖替換整個模型時嘲笑該方法模擬對象類嘲笑整個班級
@mock.patch.object
成功嘲笑scan
方法,但@mock.patch
未能這樣做。我遵循 https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch 的例子,但顯然我做錯了什麼。
我嘲笑在這兩種情況下在同一個命名空間中的詞彙模塊(它是由import lexicon
進口在sentence_parser
),但mock_lexicon is lexicon.lexicon
檢查失敗
#!python
import sys;
sys.path.append('D:\python\lexicon');
import lexicon;
import sentence_parser;
import unittest2 as unittest;
import mock;
class ParserTestCases(unittest.TestCase) :
def setUp(self) :
self.Parser = sentence_parser.Parser();
@mock.patch('lexicon.lexicon')
def test_categorizedWordsAreAssigned_v1(self, mock_lexicon) :
print "mock is lexicon:";
print mock_lexicon is lexicon.lexicon + "\n";
instance = mock_lexicon.return_value;
instance.scan.return_value = "anything";
self.Parser.categorize_words_in_sentence("sentence");
instance.scan.assert_called_once_with("sentence");
@mock.patch.object(lexicon.lexicon, 'scan')
def test_categorizedWordsAreAssigned_v2(self, mock_scan) :
mock_scan.return_value = "anything";
self.Parser.categorize_words_in_sentence("sentence");
mock_scan.assert_called_once_with("sentence");
if (__name__ == '__main__') :
unittest.main()
輸出:
mock is lexicon:
False
======================================================================
FAIL: test_categorizedWordsAreAssigned_v1 (__main__.ParserTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 1305, in patched
return func(*args, **keywargs)
File "./test_sentence_parser.py", line 26, in test_categorizedWordsAreAssigned_v1
instance.scan.assert_called_once_with("sentence");
File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 947, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'scan' to be called once. Called 0 times.
----------------------------------------------------------------------
Ran 2 tests in 0.009s
FAILED (failures=1)
編輯:
澄清,Parser
定義如下
#!python
import sys;
sys.path.append('D:\python\lexicon');
import lexicon;
class Parser(object) :
my_lexicon = lexicon.lexicon()
def __init__(self) :
self.categorized_words = ['test'];
def categorize_words_in_sentence(self, sentence) :
self.categorized_words = self.my_lexicon.scan(sentence);
if (__name__ == '__main__') :
instance = Parser();
instance.categorize_words_in_sentence("bear");
print instance.categorized_words;
三個問題:1)我接過來一看,以'lexicon'模塊在https://github.com/bitprophet/lexicon/tree/master/lexicon和接縫給我的類是'Lexicon'代替' lexicon'; 2)我的猜測是你有另一個'詞庫'模塊,而不是'D:\ python \ lexicon'中的一個; 3)爲什麼你需要';'在行尾? –
1)'詞庫'是我自己的模塊,恰好與你鏈接的名稱相同; 2)'D:\ python \ lexicon'中只有兩個文件,一個是'lexicon.py',另一個是包含unittests的'test_lexicon.py'; 3)';'只是我習慣於其他語言的東西,但這裏並沒有真正相關 – krzym1