如何在模拟方法中引用对象引用

时间:2016-06-18 21:21:49

标签: python unit-testing mocking

方式:

def analyse_sentence(self, sentence, channel):
        found_top_news = 'top news' in sentence or 'trending news' in sentence
        if found_top_news:
            categories = []
            found_categories = SharedNewsUtils.extract_categories(sentence, categories)
            if found_categories:
                result = self.retrieve_top_news(categories[0])

单元测试:

    @patch('slack.realtime_bot.plugins.news_plugin.news.News.retrieve_top_news')
    @patch('utils.shared_news_utils.SharedNewsUtils.extract_categories')
    def test_analyse_sentence_calls_retrieve_top_news_if_found_categories(self, mck, mck2):
        mck.return_value = True
        sentence = 'trending news'
        channel = 'D'
        mck2.return_value = []
        self.news.analyse_sentence(sentence, channel)
        self.assertTrue(mck2.called)

此单元测试失败并显示以下消息:

result = self.retrieve_top_news(categories[0])  IndexError: list index out of range

由于extract_categories被模拟,并且在方法中注入了一个空的categories列表,我不知道如何模拟它以便稍后防止列表超出索引。

1 个答案:

答案 0 :(得分:0)

如果extract_categories正在改变categories,那么您应该可以在测试中使用side_effect来变异categories

def mutate_categories(sentence, categories):
  categories.append('some_item')

mck.side_effect = mutate_categories