[Django]-How to mock a Django model object (along with its methods)?

35👍

Don’t patch the model itself but model.objects and then mock every part of the chain:

@patch('utils.Foo.objects')
def test_foo_something_exist_returns_none(self, mock_foo):
    # just to show how to do it with longer chains
    # mock_foo.filter.return_value = mock_foo
    # mock_foo.exclude.return_value = mock_foo            
    mock_foo.get.return_value = mock_foo
    mock_foo.exists.return_value = False

    self.assertIsNone(utils.foo_something_exist()) 

This also work’s with .filter(), .exclude() and other model operations. I also find Model Mommy really helpful when testing Django models.

Leave a comment