2016-03-29 79 views
1

我有以下代碼:懲戒同一類兩種方法

@istest 
@patch.object(Chapter, 'get_author') 
@patch.object(Chapter, 'get_page_count') 
def test_book(self, mock_get_author, mock_get_page_count): 
    book = Book() # Chapter is a field in book 

    mock_get_author.return_value = 'Author name' 
    mock_get_page_count.return_value = 43 

    book.get_information() # calls get_author and then get_page_count 

在我的代碼,get_page_count,這是get_author後調用,將返回「作者日期名稱」,而不是43.如何預期值我能解決這個問題嗎?我已經試過如下:

@patch('application.Chapter') 
def test_book(self, chapter): 
    mock_chapters = [chapter.Mock(), chapter.Mock()] 
    mock_chapters[0].get_author.return_value = 'Author name' 
    mock_chapters[1].get_page_count.return_value = 43 
    chapter.side_effect = mock_chapters 

    book.get_information() 

但後來我得到一個錯誤:

TypeError: must be type, not MagicMock 

在此先感謝您的任何建議!

回答

1

你的裝飾器使用不正確的順序,這就是爲什麼。你想從底部開始,根據你在test_book方法中設置參數的方式,爲'get_author'和'get_page_count'打補丁。

@istest 
@patch.object(Chapter, 'get_page_count') 
@patch.object(Chapter, 'get_author') 
def test_book(self, mock_get_author, mock_get_page_count): 
    book = Book() # Chapter is a field in book 

    mock_get_author.return_value = 'Author name' 
    mock_get_page_count.return_value = 43 

    book.get_information() # calls get_author and then get_page_count 

有沒有更好的辦法不是引用this優秀的答案解釋,當你使用多個裝飾究竟是發生在解釋這個其他。

+1

非常感謝! – Oreo