私は次のような機能を持っています
def getEvents(eid, request):
......
ここで、上記の関数の単体テストを(ビューを呼び出さずに)個別に記述したいと思います。では、上記をどのように呼び出す必要がありますかTestCase
。リクエストを作成することはできますか?
私は次のような機能を持っています
def getEvents(eid, request):
......
ここで、上記の関数の単体テストを(ビューを呼び出さずに)個別に記述したいと思います。では、上記をどのように呼び出す必要がありますかTestCase
。リクエストを作成することはできますか?
この解決策を参照してください:
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)
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.TestCase
(from django.test import TestCase, SimpleTestCase, TransactionTestCase
)を使用している場合は、次のように入力するだけで、任意のテストケースのクライアントインスタンスにアクセスできますself.client
。
response = self.client.get(some_url)
request = response.wsgi_request
RequestFactory
ダミーリクエストを作成するために使用します。
そうdef getEvents(request, eid)
ですか?
Django unittestを使用すると、を使用from django.test.client import Client
してリクエストを行うことができます。
ここを参照してください:クライアントのテスト
@Secatorの答えは、非常に優れた単体テストに非常に適したモックオブジェクトを作成するため、完璧です。ただし、目的によっては、Djangoのテストツールを使用する方が簡単な場合があります。
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をご覧ください。