1. Unit Tests trong Django
Unit tests tập trung vào việc kiểm tra từng phần nhỏ (đơn vị) của mã, ví dụ như một hàm, một phương thức hoặc một model cụ thể.Cách viết Unit TestsDjango sử dụng module unittest của Python, cùng với lớp TestCase được cung cấp bởi django.test.
Bước cơ bản:
- Tạo file test: Tạo một file tên tests.py trong ứng dụng Django của bạn (ví dụ: myapp/tests.py).
- Import các công cụ cần thiết: Sử dụng django.test.TestCase.
- Viết test case: Kiểm tra từng chức năng cụ thể.
Ví dụ: Kiểm tra một model
Giả sử bạn có model Book trong myapp/models.py:python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.title
Viết unit test trong myapp/tests.py:python
from django.test import TestCase
from .models import Book
class BookModelTest(TestCase):
def setUp(self):
# Thiết lập dữ liệu trước mỗi test
Book.objects.create(title="Test Book", author="Test Author", price=29.99)
def test_book_creation(self):
# Kiểm tra việc tạo Book
book = Book.objects.get(title="Test Book")
self.assertEqual(book.author, "Test Author")
self.assertEqual(float(book.price), 29.99)
def test_string_representation(self):
# Kiểm tra phương thức __str__
book = Book.objects.get(title="Test Book")
self.assertEqual(str(book), "Test Book")
- setUp: Chạy trước mỗi phương thức test để tạo dữ liệu thử nghiệm.
- assertEqual: Kiểm tra xem giá trị thực tế có khớp với giá trị mong đợi không.
Chạy test
Dùng lệnh:
python manage.py test
Django sẽ tự động tìm tất cả các file tests.py và chạy chúng.
2. Integration Tests trong Django
Integration tests kiểm tra sự tương tác giữa các thành phần khác nhau trong ứng dụng, như view, model, và template.Cách viết Integration TestsSử dụng django.test.Client để mô phỏng yêu cầu HTTP và kiểm tra phản hồi.
Ví dụ: Kiểm tra một view
Giả sử bạn có một view trong myapp/views.py:python
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'myapp/book_list.html', {'books': books})
Và template myapp/templates/myapp/book_list.html:html
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>
Viết integration test trong myapp/tests.py:python
from django.test import TestCase, Client
from .models import Book
class BookViewTest(TestCase):
def setUp(self):
self.client = Client() # Tạo một client để gửi yêu cầu HTTP
Book.objects.create(title="Book 1", author="Author 1", price=10.00)
Book.objects.create(title="Book 2", author="Author 2", price=15.00)
def test_book_list_view(self):
# Gửi yêu cầu GET đến URL của view
response = self.client.get('/books/') # Giả sử URL là '/books/'
# Kiểm tra mã trạng thái HTTP
self.assertEqual(response.status_code, 200)
# Kiểm tra nội dung template
self.assertContains(response, "Book 1 by Author 1")
self.assertContains(response, "Book 2 by Author 2")
# Kiểm tra context được truyền vào template
self.assertEqual(len(response.context['books']), 2)
- Client: Mô phỏng trình duyệt để gửi yêu cầu HTTP.
- assertContains: Kiểm tra xem phản hồi có chứa nội dung mong đợi không.
- response.context: Kiểm tra dữ liệu được truyền vào template.
Cấu hình URL
Đảm bảo URL /books/ được định nghĩa trong urls.py:python
from django.urls import path
from .views import book_list
urlpatterns = [
path('books/', book_list, name='book_list'),
]

3. Một số mẹo khi viết test
- Sử dụng setUp và tearDown: Để chuẩn bị và dọn dẹp dữ liệu.
- Test cả trường hợp lỗi: Ví dụ, kiểm tra phản hồi khi truy cập URL không tồn tại (status_code=404).
- Sử dụng assertRaises: Để kiểm tra ngoại lệ.
- Tách biệt unit và integration tests: Đặt trong các class hoặc file riêng nếu cần.
Ví dụ kiểm tra lỗi:python
def test_invalid_url(self):
response = self.client.get('/nonexistent/')
self.assertEqual(response.status_code, 404)
4. Công cụ bổ sung
- Factory Boy hoặc Faker: Để tạo dữ liệu giả lập nhanh chóng.
Coverage: Để đo mức độ bao phủ của test:bash
pip install coverage
coverage run manage.py test
coverage report
Hy vọng hướng dẫn này giúp bạn viết unit tests và integration tests trong Django một cách hiệu quả!