2

I have a model:

class Order(models.Model):

    STATUS_CHOICES = (
        (100, 'First'),
        (200, 'Second'),
    )
    status = models.IntegerField('Status', choices=STATUS_CHOICES)

    def accept(self):
        self.status = 200
        self.save()
        return self.status, self.get_status_display()

And I have a Unit-Test for it:

class CustomTestCase(TestCase):

    @classmethod
    def setUp(self):
        pass

    @classmethod
    def save(self):
        pass


class OrderTest(CustomTestCase):

    def test_accept(self):
        result = Order.accept(self)
        expected = (200, 'Second')

        self.assertEqual(expected, result)

As you can see, i added 'save' function that do nothing, the reason for that is because without that custom 'save' function I keep getting this error:

[OrderTest] object has no attribute [save]

If there is a better solution to that custom 'save' function please tell me. But this kind of solution will not work with django-built-in 'get_status_display()' function. And without solution I keep getting this trouble:

[OrderTest] object has no attribute [get_status_display]

What can I do to make this work as I need ?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
inmate_37
  • 1,218
  • 4
  • 19
  • 33

1 Answers1

5

If you want to test the accept method, just create a new Order like this:

 def test_accept(self):
    order = Order.objects.create(status=100)
    result = order.accept()
    expected = (200, 'Second')
    self.assertEqual(expected, result)

The reason why you got the [OrderTest] object has no attribute [save] error is you pass the test object into the accept method (in "Order.accept(self)"), so when self.save() is called, it actually looks for the save method of the test class.

Hope this helps.

Phuong Nguyen
  • 306
  • 2
  • 1
  • 1
    Thank you very much! But I do not understand one thing, what is a purpose of mocking, if I have to actually create objects for testing ? For example I tried to do this: order = Mock(spec=Order) and it did not work, however: order = Order.objects.create(status=100) worked perfectly. If I have to create new objects via 'Model.objects.create' for every unit-test, why even use mocking ? – inmate_37 Oct 19 '17 at 04:59
  • @Madi7 https://stackoverflow.com/questions/3622455/what-is-the-purpose-of-mock-objects – bruno desthuilliers Oct 19 '17 at 11:20