我想做的是...x = MagicMock()x.iter_values = [1, 2, 3]for i in x: i.method()我正在尝试为此功能编写单元测试,但不确定如何模拟所有调用的方法而不调用某些外部资源...def wiktionary_lookup(self): """Looks up the word in wiktionary with urllib2, only to be used for inputting data""" wiktionary_page = urllib2.urlopen( "http://%s.wiktionary.org/wiki/%s" % (self.language.wiktionary_prefix, self.name)) wiktionary_page = fromstring(wiktionary_page.read()) definitions = wiktionary_page.xpath("//h3/following-sibling::ol/li") print definitions.text_content() defs_list = [] for i in definitions: print i i = i.text_content() i = i.split('\n') for j in i: # Takes out an annoying "[quotations]" in the end of the string, sometimes. j = re.sub(ur'\u2003\[quotations \u25bc\]', '', j) if len(j) > 0: defs_list.append(j) return defs_list编辑:我不确定我是否在滥用模拟游戏。我试图对该wiktionary_lookup方法进行单元测试而不调用外部服务...所以我模拟了urlopen ..我模拟了fromstring.xpath(),但据我所知,我还需要遍历并调用方法“ xpath()”,这就是我在这里尝试做的事情。如果我完全误解了如何对该方法进行单元测试,请告诉我哪里出了问题...编辑(添加当前的单元测试代码)@patch("lang_api.models.urllib2.urlopen")@patch("lang_api.models.fromstring")def test_wiktionary_lookup_2(self, fromstring, urlopen): """Looking up a real word in wiktionary, should return a list""" fromstring().xpath.return_value = MagicMock( content=["test", "test"], return_value='test\ntest2') # A real word should give an output of definitions output = self.things.model['word'].wiktionary_lookup() self.assertEqual(len(output), 2) (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您实际要做的是不返回带有Mock的return_value=[]。您实际上想返回list个Mock个对象。这是测试代码的片段,其中包含正确的组件和一个小示例,以显示如何测试循环中的一个迭代:@patch('d.fromstring')@patch('d.urlopen')def test_wiktionary(self, urlopen_mock, fromstring_mock): urlopen_mock.return_value = Mock() urlopen_mock.return_value.read.return_value = "some_string_of_stuff" mocked_xpath_results = [Mock()] fromstring_mock.return_value.xpath.return_value = mocked_xpath_results mocked_xpath_results[0].text_content.return_value = "some string"因此,剖析上面的代码来解释为纠正您的问题所采取的措施:帮助我们测试for循环中代码的第一件事是每个创建一个模拟对象列表:mocked_xpath_results = [Mock()]然后,如您所见fromstring_mock.return_value.xpath.return_value = mocked_xpath_results我们将return_value调用的xpath设置为每个mocked_xpath_results的模拟列表。作为如何在列表中执行操作的示例,我添加了如何在循环中进行模拟,该循环显示为:mocked_xpath_results[0].text_content.return_value = "some string"在单元测试中(这可能是个观点问题),我希望保持明确,因此我要显式访问列表项并确定应该发生的情况。希望这可以帮助。 (adsbygoogle = window.adsbygoogle || []).push({}); 09-15 14:34