从同一个 class 模拟两种方法
Mocking two methods from the same class
我有以下代码:
@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
提前感谢您的任何建议!
您的装饰器使用顺序不正确,这就是原因。您希望从底部开始,根据您在 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 出色的答案来解释使用多个装饰器时究竟发生了什么,没有更好的方法来解释这一点。
我有以下代码:
@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
提前感谢您的任何建议!
您的装饰器使用顺序不正确,这就是原因。您希望从底部开始,根据您在 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 出色的答案来解释使用多个装饰器时究竟发生了什么,没有更好的方法来解释这一点。