Search code examples
django-testing

Django Test Client not working with Database calls


I'm using the django.test.Client to write tests for django's views

In the Django's view:

usr = User.objects.get(id=2)

It does not returns the User object, instead raises error ObjectDoesNotExist.

In dbshell same query works fine.

What's the catch here ?


Solution

  • Create a user in either the setUp() method of the TestCase, or add one in a fixture. Here's the setUp() version:

    class YourTestCase(TestCase):
    
        def setUp(self):
            self.user = User.objects.create(
                username='someuser',
                email='[email protected]',
                password='password'
            )
    
        def test_your_code(self):
            # now you can look it up
            user = User.objects.get(username='someuser')
            self.assertEqual(user.email, '[email protected]')