1

I am writing a test case for my model to test the __str__ but apparently it is failing.

Here is my tests.py:

from todoapp.models import User, Task
from django.test import TestCase


class UserModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(
            first_name='john',
            last_name='doe',
            email='[email protected]',
            password='johndoe')

    def test_string_representation(self):
        object_name = User.objects.get(id=50)
        expected_object_name = object_name.email
        self.assertEqual(expected_object_name, str(object_name))

Here is my models.py:

class User(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    def __str__(self):
        return self.email

P.S.: A user with id=50 already exists

1
  • 1
    If the test is failing, please show the output when you run the test. Commented Mar 20, 2019 at 10:12

1 Answer 1

3

Django creates a test database when you run the test, so it sounds like the user with id=50 doesn't exist in the test database.

You are already creating a user in the setUp method, so I suggest you fetch that user in the test.

def test_string_representation(self):
    object_name = User.objects.get(email='[email protected]')
    expected_object_name = object_name.email
    self.assertEqual(expected_object_name, str(object_name))

Note that you shouldn't usually rely on the id when fetching objects during tests. The id can change from run to run, for example if the tests run in a different order.

Sign up to request clarification or add additional context in comments.

3 Comments

It worked. Thanks a lot. Btw is the setUp method compulsory ? What should my code be if I omit it ?
If you remove the setUp method, then you'll have to create the user somewhere else, otherwise User.objects.get(...) will fail. The setUp method runs before every test in the class. If you have more than one test in the class, then putting User.objects.create(...) in the setUp method means you don't have to repeat it in every test method. Django also has setUpTestData which can be faster if you have lots of tests in the test class.
Gotcha ! Thanks mate :)

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.