2016-06-18 59 views
0

方法:如何備份參考的對象的模擬的方法內

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列表,我不知道如何嘲笑這一點,以便稍後阻止列表超出索引。

回答

0

如果extract_categories在變異categories那麼你應該能夠使用side_effect在測試變異categories

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

mck.side_effect = mutate_categories 
相關問題