我有以下代码:
@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
Run Code Online (Sandbox Code Playgroud)
在我的代码中,在 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()
Run Code Online (Sandbox Code Playgroud)
但后来我收到一个错误:
TypeError: must be type, not MagicMock
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的任何建议!
您的装饰器使用顺序不正确,这就是原因。您希望从底部开始,根据您在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
Run Code Online (Sandbox Code Playgroud)
除了引用这个优秀的答案来解释使用多个装饰器时到底发生了什么之外,没有更好的方法来解释这一点。