2016-02-15 63 views
0

這是我的簡單測試類,運行這個測試,而我得到Asse田:404 = 200Django的Asse田: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

是什麼看法呢?它可以返回404本身嗎?顯示代碼。 –

+0

在你的測試中,和Django中的urls.py一樣嗎? –

回答

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)