65

私は次のような機能を持っています

def getEvents(eid, request):
    ......

ここで、上記の関数の単体テストを(ビューを呼び出さずに)個別に記述したいと思います。では、上記をどのように呼び出す必要がありますかTestCase。リクエストを作成することはできますか?

4

5 に答える 5

105

この解決策を参照してください:

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)
于 2012-04-23T09:21:37.940 に答える
43

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
于 2015-09-01T11:49:24.060 に答える
12

RequestFactory ダミーリクエストを作成するために使用します。

于 2012-04-23T09:29:25.543 に答える
0

そうdef getEvents(request, eid)ですか?

Django unittestを使用すると、を使用from django.test.client import Clientしてリクエストを行うことができます。

ここを参照してください:クライアントのテスト

@Secatorの答えは、非常に優れた単体テストに非常に適したモックオブジェクトを作成するため、完璧です。ただし、目的によっては、Djangoのテストツールを使用する方が簡単な場合があります。

于 2012-04-23T09:23:17.497 に答える
0

djangoテストクライアントを使用できます

from django.test import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
response = c.get('/customer/details/')
response.content

詳細については、
https://docs.djangoproject.com/en/1.11/topics/testing/tools/#overview-and-a-quick-exampleをご覧ください。

于 2017-05-11T12:36:39.637 に答える