2012-04-23 97 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 
相关问题