Oreo
Oreo

Reputation: 51

Mocking two methods from the same class

I have the following code:

@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

In my code, get_page_count, which is called after get_author, is returning 'Autor name' instead of the expected value of 43. How can I fix this? I've tried the following:

@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()

But then I get an error:

TypeError: must be type, not MagicMock

Thanks in advance for any suggestions!

Upvotes: 5

Views: 4262

Answers (1)

idjaw
idjaw

Reputation: 26600

Your decorator usage is not in the right order, that is why. You want, starting from the bottom, working up, patch for 'get_author', then 'get_page_count' based on how you are setting your arguments in your test_book method.

@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

There is no better way to explain this other than referencing this excellent answer to explain what exactly is happening when you use multiple decorators.

Upvotes: 8

Related Questions