Vai
Vai

Reputation: 353

Django testcase to test models failing

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

Upvotes: 1

Views: 156

Answers (1)

Alasdair
Alasdair

Reputation: 308809

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.

Upvotes: 3

Related Questions