我有一个基于类的视图定义为:
class Myview(LoginRequiredMixin, View):
def post():
#.......
测试此视图我试过这个
class MyViewTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User.objects.create_user(
username='jacob', email='soos@i.com', password='vvggtt')
def view_test(self):
# Create an instance of a POST request.
request = self.factory.post('/my-url/')
request.user = self.user
response = MyView(request)
print (response,"**")
self.assertEqual(response.status_code, 200)
但是这会产生这个错误。
response = MyView(request)
TypeError: __init__() takes 1 positional argument but 2 were given
我理解为什么会出现这个错误(MyView的cinstructor有2个ars),但我该怎么删除呢?我无法获得有关搜索的详细信息。
答案 0 :(得分:0)
尝试
response = MyView(request=request)
答案 1 :(得分:0)
我们可以使用django test client
from django.test import Client
class MyViewTest(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create_user(
username='jacob', email='soos@i.com', password='vvggtt')
def view_test(self):
# Create an instance of a POST request.
self.client.login(username="jacob", password="vvggtt")
data = {'name': 'test name'}
res = self.client.post('/my-url/', data)
print(res)
self.assertEqual(res.status_code, 200)
答案 2 :(得分:0)
来自docs:
# Use this syntax for class-based views.
response = MyView.as_view()(request)