Avinash KS
Avinash KS

Reputation: 1

Django AssertionError: 404 != 200 in simple unit test class

This is my Simple Test class,while running this test I am getting AssertionError: 404 != 200

class SimpleTest(unittest.TestCase):
def setUp(self):
    # Every test needs a client.
    self.client = Client()

def test_details(self):
    # Issue a GET request.
    response = self.client.get('/men/ethnic-wear/')
    print "code:",response.status_code
    # Check that the response is 200 OK.
    self.assertEqual(response.status_code, 200)

But if I test the same thing in Django shell it is returning status code 200.

In [21]: from django.test import Client

In [22]: c = Client()

In [23]: response = c.get('/men/ethnic-wear/')

In [24]: response.status_code
Out[24]: 200

First time I am writing unit test script referring official document ,is there any problem with my views?

Upvotes: 0

Views: 4067

Answers (1)

Ahmed Hosny
Ahmed Hosny

Reputation: 1172

It seams that you are trying to fetch an object that is not there in test db. Note that unit-tests create its own database which is empty. What you need to do is just adding objects to test database in setUp function.

As a Prototype:

class SimpleTest(unittest.TestCase):
    def setUp(self):
        # Every test needs a client.
        self.client = Client()
        Men.objects.create('''whatever attributes here''')
        # and so on. for each prerequisite that should be there in db

    def test_details(self):
        # Issue a GET request.
        response = self.client.get('/men/ethnic-wear/')
        print "code:",response.status_code
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

Upvotes: 2

Related Questions