0

I have some Django models I need some unit test coverage on and in doing so I mock out some instances of them. Here is an example class I want coverage of

class MyMixin(object):
    @property
    def sum(self):
        return field_one + field_two + field_three

class MyModel(Model, MyMixin):

    field_one = IntegerField()
    field_two = IntegerField()
    field_three = IntegerField()

So I can mock out an instance of it like so:

mock_inst = mock.Mock(spec=MyModel, field_one=1, field_two=2, field_3=3)

However when I go to execute mock_inst.sum, it doesn't execute the code properly, it gives me something from the mock class. Shouldn't it execute the code given the spec in the instance? Is there a way to dictate to the mock that I want it to execute that code (or any other code)?

2 Answers 2

1

As Daniel says in his answer, you don't need to use a mock object here, just create an instance of the model (you don't even need to save it to the database in this case). Then access the property, and check that it gives the required output.

def test_sum(self):
    my_model = MyModel(field_one=1,
                       field_two=2,
                       field_three=3,
                       )
    self.assertEqual(my_model.sum, 6)
Sign up to request clarification or add additional context in comments.

Comments

1

No, why would you think that? The whole point of a mock is that it replaces the object with a fake version. That fake version can't - and shouldn't - run any of the code in the actual class.

2 Comments

Okay...is there an easy way to make it run that code on that instance?
Yes: don't use a mock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.