一种可能的原因是测试数据的格式不正确,可以检查测试数据是否与视图所需的格式匹配。另外,需要确保视图和测试代码都使用相同的请求方法,例如get、post等。
以下是一个示例视图和测试,用于检查输入的用户名是否已经存在:
视图代码:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class UserExistsView(APIView):
def post(self, request):
username = request.data.get("username")
if User.objects.filter(username=username).exists():
return Response({"exists": True}, status=status.HTTP_200_OK)
else:
return Response({"exists": False}, status=status.HTTP_404_NOT_FOUND)
测试代码:
from django.urls import reverse
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from rest_framework import status
class UserExistsViewTestCase(APITestCase):
url = reverse('user-exists')
def setUp(self):
self.user = User.objects.create(username='testuser', password='testpass')
def test_user_exists(self):
response = self.client.post(self.url, {"username": "testuser"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(response.data["exists"])
def test_user_does_not_exist(self):
response = self.client.post(self.url, {"username": "nonexistentuser"})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertFalse(response.data["exists"])
这里使用了reverse()函数来获取视图的URL,在setUp()方法中创建了一个测试用户。在test_user_exists()测试中,发送一个包含已经存在的用户名的POST请求,期望返回200状态码和存在的True值。在test_user_does_not_exist()测试中,发送一个包含不存在的用户名的POST请求,期望返回404状态码和存在的False值。如果测试返回400错误,则需要检查请求数据是否与视图所需的格式匹配。