Django AssertionError:404!= 200在简单的单元测试类中

时间:2016-02-15 11:54:02

标签: python django unit-testing django-unittest

这是我的Simple Test类,在运行此测试时,我得到 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)

但是如果我在Django shell中测试相同的东西,它将返回状态代码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

我第一次编写单元测试脚本参考官方文档,我的观点有问题吗?

1 个答案:

答案 0 :(得分:0)

它正在尝试获取测试数据库中不存在的对象。请注意,单元测试会创建自己的数据库,该数据库为空。您需要做的只是在setUp函数中添加对象以测试数据库。

作为原型:

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)