sedavidw
sedavidw

Reputation: 11721

Mock instance isn't using property code

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)?

Upvotes: 0

Views: 35

Answers (2)

Alasdair
Alasdair

Reputation: 309029

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)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599796

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.

Upvotes: 1

Related Questions