Skip to main content

Unit Testing: A Real World Test

by Raoul Snyman 2017-03-22 05:00:29 UTC

This is a cast showing how I wrote a real world test for the song maintenance for in OpenLP.

I needed to mock out a number of the methods and objects in the method in order to remove external dependencies that I don't want to influence the test. At the end of the day I did have a few issues when trying to run the test, and the final result is posted below for your perusal.

@patch('openlp.plugins.songs.forms.songmaintenanceform.QtWidgets.QListWidgetItem')
@patch('openlp.plugins.songs.forms.songmaintenanceform.Author')
def test_reset_authors(self, MockedAuthor, MockedQListWidgetItem):
    """
    Test the reset_authors() method
    """
    # GIVEN: A mocked authors_list_widget and a few other mocks
    mocked_author1 = MagicMock()
    mocked_author1.display_name = 'John Newton'
    mocked_author1.id = 1
    mocked_author2 = MagicMock()
    mocked_author2.display_name = None
    mocked_author2.first_name = 'John'
    mocked_author2.last_name = 'Wesley'
    mocked_author2.id = 2
    mocked_authors = [mocked_author1, mocked_author2]
    mocked_author_item1 = MagicMock()
    mocked_author_item2 = MagicMock()
    MockedQListWidgetItem.side_effect = [mocked_author_item1, mocked_author_item2]
    MockedAuthor.display_name = None
    self.mocked_manager.get_all_objects.return_value = mocked_authors

    # WHEN: reset_authors() is called
    with patch.object(self.form, 'authors_list_widget') as mocked_authors_list_widget:
        self.form.reset_authors()

    # THEN: The authors list should be reset
    expected_widget_item_calls = [call('John Newton'), call('John Wesley')]
    mocked_authors_list_widget.clear.assert_called_once_with()
    self.mocked_manager.get_all_objects.assert_called_once_with(MockedAuthor,
                                                                order_by_ref=MockedAuthor.display_name)
    assert MockedQListWidgetItem.call_args_list == expected_widget_item_calls, MockedQListWidgetItem.call_args_list
    mocked_author_item1.setData.assert_called_once_with(QtCore.Qt.UserRole, 1)
    mocked_author_item2.setData.assert_called_once_with(QtCore.Qt.UserRole, 2)
    mocked_authors_list_widget.addItem.call_args_list == [
        call(mocked_author_item1), call(mocked_author_item2)]