【问题标题】:Mocking two methods from the same class模拟来自同一类的两个方法
【发布时间】:2016-07-17 16:42:02
【问题描述】:

我有以下代码:

@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_author 之后调用的 get_page_count 返回“Autor name”而不是预期值 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

提前感谢您的任何建议!

【问题讨论】:

    标签: python mocking


    【解决方案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 出色的答案来解释使用多个装饰器时到底发生了什么之外,没有更好的方法来解释这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2014-04-08
      • 2017-01-05
      • 1970-01-01
      相关资源
      最近更新 更多