2016-03-29 47 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