我有以下代码:
@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之后调用)返回'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
提前感谢任何建议!
答案 0 :(得分:3)
你的装饰用法用法不正确,这就是原因。你想要,从底部开始,准备工作,修补' get_author',然后' get_page_count'根据您在test_book
方法中设置参数的方式。
@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优秀的答案来解释使用多个装饰器时究竟发生了什么,没有更好的方法来解释这一点。