【发布时间】:2015-11-11 21:39:28
【问题描述】:
长话短说,当它只是被模拟对象替换的那个方法时,我完全能够模拟类方法,但是当我试图用模拟替换整个类时我无法模拟那个方法对象
@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) 我在github.com/bitprophet/lexicon/tree/master/lexicon 上查看了
lexicon模块,我发现课程是Lexicon而不是lexicon; 2) 我的猜测是你有另一个lexicon模块,而不仅仅是D:\python\lexicon中的那个; 3)为什么在行尾需要;? -
1)
lexicon是我自己的模块,恰好与您链接的模块同名; 2)我在D:\python\lexicon中只有两个文件,一个是lexicon.py,第二个是test_lexicon.py,包含单元测试; 3);只是我在其他语言中习惯的东西,但这在这里并不重要
标签: python python-2.7 unit-testing mocking