python-模拟来自同一类的两个方法
作者:互联网
我有以下代码:
@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返回“自动名称”,而不是期望值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
在此先感谢您的任何建议!
解决方法:
这是为什么您的装饰器使用顺序不正确.您需要从底部开始对“ get_author”进行修补,然后根据在test_book方法中设置参数的方式对“ 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最佳答案来解释使用多个装饰器时到底发生了什么,没有比这更好的方法了.
标签:mocking,python 来源: https://codeday.me/bug/20191118/2031496.html