首先django中有3個測試cmd命令。
1.python manage.py test:執(zhí)行所有的測試用例
2.python manage.py test app_name:執(zhí)行該app的所有測試用例
3.python manage.py test app_name.case_name: 執(zhí)行指定的測試用例,該條可用于只測試tests.py中的一個類 (實際測試無效果.過會再試)
對models中的方法進行測試
1.在app路徑下的tests.py中添加一個測試類
2.編寫測試的方法.要以test為前綴開頭,并繼承TestCase 這相當于python中的unittest
3.對需要預料到的結果進行斷言測試.這里用的例子是對Question模塊中was_published_recently()方法進行單元測試
如果有測試錯誤.會把異常顯示在控制臺.
這個過程是 1.首先運行python manage.py test blog 對blog這個app進行單元測試?
2.發(fā)現(xiàn)有django.test.TestCase這個類的子類
3.生成一個臨時的數(shù)據(jù)庫進行測試.
4.查找測試類中已test開頭的測試方法.
5.使用斷言assertIs() 來進行測試判斷
對was_published_recently 完整的進行測試
對view進行測試
有2種.第一種直接在shell中測試.不寫了.
在test中進行測試
首先要在views.py中設置下,讓主頁對時間在未來的Question不進行顯示
這里要對IndexView跟DetailView共同配置, 否則index不顯示了在detail中可以根據(jù)Question的id猜到url讓detail.index把未來的Question 暴露出來.
pub_date__lte 表示<=?
編寫對view進行單元測試的代碼
這里編寫各種邏輯,比如Question的入庫時間在未來index.html會怎么顯示.在過去入庫又會怎樣怎樣.考慮各種情況寫對應的斷言
這里有2個django新增加的的斷言
assertQuerysetEqual():
assertContains():
Intest_past_question, we create a question and verify that it appears in the list.
Intest_future_question, we create a question with apub_datein the future. The database is reset for each test method, so the first question is no longer there, and so again the index shouldn’t have any questions in it.
這里有一個坑.自帶文檔沒用mysql,用的自帶的數(shù)據(jù)庫.所以要在代碼中加入save()才能獲取到下面的<Question: Past question>