2012-04-23 77 views

回答

64

this solution

from django.utils import unittest 
from django.test.client import RequestFactory 

class SimpleTest(unittest.TestCase): 
    def setUp(self): 
     # Every test needs access to the request factory. 
     self.factory = RequestFactory() 

    def test_details(self): 
     # Create an instance of a GET request. 
     request = self.factory.get('/customer/details') 

     # Test my_view() as if it were deployed at /customer/details 
     response = my_view(request) 
     self.assertEqual(response.status_code, 200) 
+4

該代碼實際上已經從1.3版本包含在Django。請參閱此處的[文檔](https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.client.RequestFactory)。 – 2012-04-23 09:28:58

+1

如果我正確地看到此錯誤,那麼來自工廠的假請求不會通過中間件進行過濾。 – 2014-09-08 10:01:52

+3

更新文檔[鏈接](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#example) – dragonx 2016-05-06 05:49:34

0

你的意思是def getEvents(request, eid)吧?

使用Django unittest,您可以使用from django.test.client import Client來提出請求。

在這裏看到:Test Client

@ Secator的答案是知府,因爲它創造這實在是首選一個很好的單元測試模仿對象。但根據你的目的,使用Django的測試工具可能更容易。

11

使用RequestFactory創建一個虛擬請求。

+1

感謝您鏈接到doc – 2015-10-08 15:07:07

13

如果使用django的測試客戶端(from django.test.client import Client),可以像這樣從響應對象訪問請求:

from django.test.client import Client 

client = Client() 
response = client.get(some_url) 
request = response.wsgi_request 

,或者如果使用的是django.TestCasefrom django.test import TestCase, SimpleTestCase, TransactionTestCase)可以在任意的測試用例僅通過訪問客戶端實例鍵入self.client

response = self.client.get(some_url) 
request = response.wsgi_request